Chap4 Exceptionhandling
Chap4 Exceptionhandling
Exception Handling
Exception Handling
Topics covered:
What exceptions are and how they’re
handled
The exception class hierarchy
When to use exception handling:
try blocks to delimit code in which
exceptions might occur
throw exceptions to indicate a problem
catch blocks to specify exception
handlers
finally block to release resources
Exception Handling
Exception
Exception
Checked
exceptio
n
Unchecke
d
exception
Exception Handling
try The "try" keyword is used to specify a block where we should place
exception code. The try block must be followed by either catch or
finally. It means, we can't use try block alone.
catch The "catch" block is used to handle the exception. It must be
preceded by try block which means we can't use catch block alone. It
can be followed by finally block later.
finally The "finally" block is used to execute the important code of the
program. It is executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It doesn't throw
an exception. It specifies that there may occur an exception in the
method. It is always used with method signature.
Exception Handling
Syntax:
try{
//code that may throw an exception
try-catch }
block catch(Exception_class_Name ref){
//code to respond to exception
};
try{
//code that may throw an exception
try-finally }
block finally(Exception_class_Name ref){
//code to respond to exception
};
Example - Exception Handling
Example – finally block
Exception Handling
Example