File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes need help on Exceptions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "need help on Exceptions" Watch "need help on Exceptions" New topic
Author

need help on Exceptions

Chris Wox
Ranch Hand

Joined: May 25, 2006
Posts: 34
class Exc1 extends Exception{ }

public class Test {
static void a() {
try {
System.out.print("Try ");
}
catch(Exc1 e) {
System.out.print("Catch ");
}
finally {
System.out.println("Finally ");
}
}

I am getting compile error on the above saying:

exception exc1 is never thrown in the body of corresponding try statement


but when I change the catch to as below then I dont get compiler erorr ???
catch(Exception e) {
System.out.print("Catch ");


please help me understand this rule . thanks
Naseem Khan
Ranch Hand

Joined: Apr 25, 2005
Posts: 809

class Exc1 extends Exception{ }

public class Test {
static void a() {
try {
System.out.print("Try ");
}
catch(Exc1 e) {
System.out.print("Catch ");
}
finally {
System.out.println("Finally ");
}
}

I am getting compile error on the above saying:

exception exc1 is never thrown in the body of corresponding try statement



If you are catching any unchecked exception i.e., RuntimeException and suppose try statements are not throwing that type of exception, then program will still compile.

e.g.,



However, if you are catching checked exceptions and if try statements are not throwing the exception, you will get compilation error.

Like in this...



In your case, how compiler will decide whether Exc1 is a checked or unchecked?. Your class could be just like IOException. You know for checked you can only catch it when it is really thrown.

Thats why you are getting compilation error in that case.


but when I change the catch to as below then I dont get compiler erorr ???
catch(Exception e) {
System.out.print("Catch ");



Since Exception covers unchecked as well, compiler will not give any error at compilation time.

You can also make compiler happy by extending RuntimeException instaed of Exception like this...




Naseem


Asking Smart Questions FAQ - How To Put Your Code In Code Tags
Chris Wox
Ranch Hand

Joined: May 25, 2006
Posts: 34
wow , the best possible explanation ! thanks a lot
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: need help on Exceptions