Sunday, July 4, 2010

Try, Catch, Throw, Throws, and Finally

Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.


• Program statements that you want to monitor for exceptions are contained within a try block. If an exception occurs within the try block, it is thrown.

• Your code can catch this exception (using catch) and handle it in some rational manner. System-generated exceptions are automatically thrown by the Java run-time system.

• To manually throw an exception, use the keyword throw.

• Any exception that is thrown out of a method must be specified as such by a throws clause.

• Any code that absolutely must be executed before a method returns is put in a finally block.

try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
........
.... ...
finally {
    // block of code to be executed before try block ends
}

No comments:

Post a Comment