Thursday, 8 March 2012

Using exception handling keywords

Using try and catch:



Multiple “catch” blocks:

•The “catch” block must immediately follow a “try” block.
•There can be multiple “catch” blocks for a single “try” block, because the code in the try block may raise more than one exception.
•When writing multiple “catch” blocks, the subclass exceptions must be written before the superclass exceptions. If they are not written in such a way, all the exceptions will be handled by the superclass exception type only.

Nested “try” blocks:

•A “try” block can be declared inside another “try” block.
•The exceptions raised inside a inner “try” block are matched against the “catch” blocks of the inner try block. If there are no “catch” blocks matching the type of exception, then the “catch” blocks of the outer “try” block are matched.
•If none of the “catch” blocks match, then the Java run-time system invokes its default provider which prints the stack trace.

“throw” keyword:




“throws” keyword:

•If a method may raise checked exception(s) and doesn’t provide any handlers for handling the checked exceptions, we use “throws” keyword to guard the calling methods.
•The “throws” keyword is declared within the method declaration.
•The “throws” keyword specifies the types of exceptions that the method might throw.
•There is no need for the method to throw exceptions of the type “Error” and “RuntimeException” or any of their sub classes.




“finally” keyword:

No comments:

Post a Comment