It's not a secret anymore!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Confusion on Exception handling 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 "Confusion on Exception handling " Watch "Confusion on Exception handling " New topic
Author

Confusion on Exception handling

Ashok Pradhan
Ranch Hand

Joined: Dec 17, 2007
Posts: 180

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

Joined: May 17, 2008
Posts: 20
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

Joined: Apr 16, 2004
Posts: 201
ya, as Jamie MacDonald has explained. Its not important to know only one rule its necessary to know all the rules.


SCJP 96% | SCWCD 90%| SCJP mock exams | My SCJP blog
Ashok Pradhan
Ranch Hand

Joined: Dec 17, 2007
Posts: 180

Thanks Jamie,Now I got it.
 
wood burning stoves
 
subject: Confusion on Exception handling
 
Similar Threads
Exception from Initializer block
Catching non-thrown exceptions
Reg. Exceptions in finally block
Exceptions - handle or declare rule
wizlab mock question