• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

need help on Exceptions

 
Chris Wox
Ranch Hand
Posts: 34
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 809
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
 
Chris Wox
Ranch Hand
Posts: 34
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
wow , the best possible explanation ! thanks a lot
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic