Professional Documents
Culture Documents
Object Oriented Programming: With Java
Object Oriented Programming: With Java
With Java
Exception Handling
Exception ?
2 www.ru.ac.bd/cse/~az
Exception Handling
Suppose an error occurs while a Java program is running. The error might be caused by
a file containing wrong information, a flaky network connection, or use of an invalid array index or an attempt to use an object reference that hasn't yet been assigned to an object.
3 www.ru.ac.bd/cse/~az
Exception Handling
Return to a safe state and enable the user to execute other commands;
or
Allow the user to save all his or her work and terminate the program gracefully.
4 www.ru.ac.bd/cse/~az
Exception Handling
to transfer control
To handle exceptional situations you must take into account the errors and problems that may occur.
Exception Handling
Int char <=1 // 0 Busy /unavailable Memory not enough Programming error
Device errors
Physical limitations...
Code Errors
6 www.ru.ac.bd/cse/~az
Exception Handling
7 www.ru.ac.bd/cse/~az
8 www.ru.ac.bd/cse/~az
Exception Handling
To catch an exception, you set up a try/catch block. The simplest form of the try block is as follows:
9 www.ru.ac.bd/cse/~az
Exception Handling
If any of the code inside the try block throws an exception of the class specified in the catch clause, then,
1. 2.
The program skips the remainder of the code in the try block;
The program executes the handler code inside the catch clause.
10 www.ru.ac.bd/cse/~az
Exception Handling
If none of the code inside the try block throws an exception, then the program skips the catch clause. If any of the code in a method throws an exception of a type other than the one named in the catch clause, this method exits immediately.
11 www.ru.ac.bd/cse/~az
12 www.ru.ac.bd/cse/~az
Exception Handling
13 www.ru.ac.bd/cse/~az
finally block
Programs that obtain certain types of resources must return them ~ to avoid ~ resource leaks
14 www.ru.ac.bd/cse/~az
Exception Handling
a finally block will execute whether or not an exception is thrown in the corresponding try block or any of its corresponding catch blocks. a finally block (if one is present) will execute if a try block exits by using
The finally block will not execute if the application exits early from a try block by calling method System.exit.
15 www.ru.ac.bd/cse/~az