aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Exception" Watch "Exception" New topic
Author

Exception

Arathi Rajashekar
Ranch Hand

Joined: Nov 20, 2001
Posts: 112
Hi,
I am bit confused. Tell me if a block of code doesnot throw any exception, its valid to enter in try and catch block right. But sometime back, when I wrote some code, it gave me compiler error, saying that it is not throwing any exception, so there is no need of try or catch block. It will be good if somebody explains me with code.
Thanks in advance


Arathi<br />Sun Certified Java Programmer
Shivaji Marathe
Ranch Hand

Joined: Jan 11, 2002
Posts: 203
Arathi :
I believe, the code you write inside
your try{} block must throw the kind of exception that you are catching in your catch block.
If you write

then the compiler will complain.
This is the message I get
Foo.java:9: Exception java.io.IOException is never thrown in the body of the corresponding try statement.
catch (IOException e){ // some exception catching code here
^
HTH
[ January 16, 2002: Message edited by: Shivaji Marathe ]
[ January 16, 2002: Message edited by: Shivaji Marathe ]
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
This rule doesn't apply for a non checked exception.
However an instance of Exception can be caught without being thrown.


SCJP2. Please Indent your code using UBB Code
Ragu Sivaraman
Ranch Hand

Joined: Jul 20, 2001
Posts: 464
Originally posted by Arathi Rajashekar:
Hi,
I am bit confused. Tell me if a block of code doesnot throw any exception, its valid to enter in try and catch block right. But sometime back, when I wrote some code, it gave me compiler error, saying that it is not throwing any exception, so there is no need of try or catch block. It will be good if somebody explains me with code.
Thanks in advance


If you catch an non-checked exception , without throwing it or calling/doing anything that can throw it in your try block then you will get a compile time error

However if the exception is non-checked like nullptr or class cast then it doesnt matter wheather you catch or not , it will still compile becoz the programmer is not obligated to do it at compile time
Ragu
Maulin Vasavada
Ranch Hand

Joined: Nov 04, 2001
Posts: 1871
hi all,
that was a good point. i didn't know that.
regards
maulin
 
 
subject: Exception