Monday, July 2, 2012

Unusual things in Exceptions


I called this post "Unusual things in Exceptions" because you're going to see something that isn't usually used in a real word as well as staffs that you have to memorize for the OCJP certification.

Let's start with the class hierarchy:



The code above does not compile you cannot handle an exception if the block try does not "throw" one.

!Import
The block finally always is called, even if there is a return statement in the try/catch block, the finally block will be executed before the return stamement.


In this case the block try "throws" an exception throught the creation of FileOutputStream, but we still getting a compiler error, because the catch that handles FileNotFoundException will never be reached.

That's the rule for checked exceptions if you throw an exception you must declare(throws) from the calling method or catch(try/catch).


Different from checked exception, every exception under RuntimeException/Error are not obligated to catch or declare, but if you did you would be able to catch it by using try/catch block.

Common Exception

Let's take a look at the common exception, watch out where they come from





No comments: