Exception Handling
Exception Handling
C.SAGANA
AP(SrG)/CSE
Exception
• unwanted or unexpected event, which occurs
during the execution of a program
or
• event that disrupts the normal flow of the
program. It is an object which is thrown at
runtime
Exception Handling
• handle the runtime errors
• exception handling is managed via five keywords:
• try, catch, throw, throws, and finally
• Try
– Program statements need to be monitored for exception should be placed in
try block
– must be followed by either catch or finally
• Catch
– Catch the thrown exception and handle them
• Throw
– Throws the exceptions occurred
• Throws
– Used in methods, that does not use try, catch
• Finally
– Code that should be executed after try/catch should be written in finally block
– executed whether an exception is handled or not.
Syntax
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 after try block ends
}
Advantage of Exception Handling
• maintain the normal flow of the application
• Example
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;