Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

exceptions

 
Fran Kindred
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One of dan chisolm exam question answers

A compile-time error is generated, because the second catch clause attempts to catch an exception that is never thrown in the try block.


But I tried this code and it seems to work fine

 
Steven Bell
Ranch Hand
Posts: 1071
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried this with a method that throws IOException. I did a catch on the IOException followed by a catch on the Exception. This compiled and ran fine.

It might help to know the specific throw and catch clauses for the problem.

I know that order of Exceptions is important and enforced by the compiler.

I know that if you try to catch something that is not thrown, and is not a superclass or subclass of what is thrown, you will get a compiler error.

example:


This will show an error because a SQLException cannot be thrown.
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried this code and it seems to work fine:

try{
}catch (IllegalArgumentException e){
}
catch(Exception e){
}


IllegalArgumentException is an unchecked exception. javac does not keep track of where it might be thrown. So the rule that a catch block for an exception that will never be thrown is an unreachable statement is unenforcable for unchecked exceptions.
 
Edwin Dalorzo
Ranch Hand
Posts: 961
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This code actually does not produce any compile-time error:

try{ }
catch (IllegalArgumentException e){}
catch(Exception e){}

However, if write it this way it does:

try{ }
catch(Exception e){}
catch (IllegalArgumentException e){}

Because any IllegalArgumentException will be caught by the Exception catch block since this is a super class of IllegalArgumentException.
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
any IllegalArgumentException will be caught by the Exception catch block since this is a super class of IllegalArgumentException.

Yes, there is the rule that a catch clause should not be completely shadowed by a preceding catch clause.

There is also a rule against unreachable statements. One such case is a catch clause specifying an exception that will never be thrown in the associated try block. javac enforces this for catch clauses specifying checked exceptions like IOException and InterruptedException. However, javac does not verify that unchecked exceptions like IllegalArgumentException or mixed exceptions like Exception can actually be thrown in the associated try block.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic