• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Confusion on Exception handling

 
Ashok Pradhan
Ranch Hand
Posts: 180
Eclipse IDE Firefox Browser Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In K&B pg.349 it is given that:-
It is illegal to use a try clause without either a catch clause or a finally clause.A try clause by itself will result in a compiler error.Any catch clauses must immediately follow the try block.Any finally clause must immediately follow the last catch clause (or it must immediately follow the try block if there is no catch) It is legal to omit either the catch clause or the finally clause, but not both.

but my program does not compile :-
class NewException extends Exception
{}
class Test
{
public static void main(String[] args)
{
go(20);
}
public static void go(int i)
{
NewException ex = new NewException();
if(i<10)
try
{
throw ex;
}
finally
{}
}
}

C:\Test.java:15: unreported exception NewException; must be caught or declared to be thrown
throw ex;
^
1 error

Process completed.

I know that i am throwing a checked exception so that it should declared to be thrown or must be caught.

Is that mean P:-It is legal to omit either the catch clause or the finally clause, but not both. is not applied to checked exceptions,you must have to catch it or declared to be thrown.

please clarify my doubts.....
 
Jamie MacDonald
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are trying to apply the statement ("It is legal to omit either the catch clause or the finally clause, but not both.") to a different context from the one in which it is intended. If you have a try clause, you must have either a catch, or a finally clause, or both. That is necessary, but not sufficient to make the compiler happy. (The compiler is only happy if you obey all its rules, not just one of them.) You must still follow the "catch or declare" rules for checked exceptions.
 
Sandeep Bhandari
Ranch Hand
Posts: 201
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ya, as Jamie MacDonald has explained. Its not important to know only one rule its necessary to know all the rules.
 
Ashok Pradhan
Ranch Hand
Posts: 180
Eclipse IDE Firefox Browser Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jamie,Now I got it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic