Week 11 - Exception Handling
Week 11 - Exception Handling
Exceptions Handling
In this module we will see try-catch block which is used for exception handling.
Try block
The try block contains set of statements where an exception can occur. A try block is always
followed by a catch block, which handles the exception that occurs in associated try block. A
try block must be followed by catch blocks or finally block or both.
try{
//statements that may cause an exception
}
While writing a program, if you think that certain statements in a program can throw an exception,
enclosed them in try block and handle that exception
Catch block
A catch block is where you handle the exceptions, this block must follow the try block. A single
try block can have several catch blocks associated with it. You can catch different exceptions
in different catch blocks. When an exception occurs in try block, the corresponding catch block
that handles that particular exception executes. For example if an arithmetic exception occurs
in try block then the statements enclosed in catch block for arithmetic exception executes.
try
{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}
Example: try catch block
If an exception occurs in try block then the control of execution is passed to the corresponding catch
block. A single try block can have multiple catch blocks associated with it, you should place the catch
blocks in such a way that the generic exception handler catch block is at the last(see in the example
below).
The generic exception handler can handle all the exceptions but you should place is at the end, if you
place it at the before all the catch blocks then it will display the generic message. You always want to
give the user a meaningful message for each type of exception rather then a generic message.
class Example1 {
public static void main(String args[]) {
int num1, num2;
try {
1|P ag e
Object Oriented Programming
Exceptions Handling
The example we seen above is having multiple catch blocks, lets see few rules about multiple catch
blocks with the help of examples. To read this in detail, see catching multiple exceptions in java.
1. As I mentioned above, a single try block can have any number of catch blocks.
2. A generic catch block can handle all the exceptions. Whether it is ArrayIndexOutOfBoundsException
or ArithmeticException or NullPointerException or any other type of exception, this handles all of
them.
catch(Exception e){
//This catch block catches all the exceptions
}
If you are wondering why we need other catch handlers when we have a generic that can handle all.
This is because in generic exception handler you can display a message but you are not sure for which
type of exception it may trigger so it will display the same message for all the exceptions and user may
not be able to understand which exception occurred. Thats the reason you should place is at the end
of all the specific exception catch blocks
3. If no exception occurs in try block then the catch blocks are completely ignored.
4. Corresponding catch blocks execute for that specific type of exception: catch(ArithmeticException
e) is a catch block that can hanlde ArithmeticException catch(NullPointerException e) is a catch block
that can handle NullPointerException.
2|P ag e
Object Oriented Programming
Exceptions Handling
Warning: ArithmeticException
Out of try-catch block...
In the above example there are multiple catch blocks and these catch blocks executes sequentially
when an exception occurs in try block. Which means if you put the last catch block ( catch(Exception
e)) at the first place, just after try block then in case of any exception this block will execute as it can
handle all exceptions. This catch block should be placed at the last to avoid such situations.
In this guide, we will see finally block which is used along with try-catch. A finally block contains all
the crucial statements that must be executed whether exception occurs or not. The statements
present in this block will always execute regardless of whether exception occurs in try block or not
such as closing a connection, stream etc.
try {
//Statements that may cause an exception
}
catch {
//Handling exception
}
finally {
//Statements to be executed
}
A Simple Example of finally block
Here you can see that the exception occurred in try block which has been handled in catch block, after
that finally block got executed.
3|P ag e
Object Oriented Programming
Exceptions Handling
class Example
{
public static void main(String args[]) {
try{
int num=121/0;
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("Number should not be divided by zero");
}
/* Finally block will always execute
* even if there is no exception in try block
*/
finally{
System.out.println("This is finally block");
}
System.out.println("Out of try-catch-finally");
}
}
Output:
1. A finally block must be associated with a try block, you cannot use finally without a try block. You
should place those statements in this block that must be executed always.
2. Finally block is optional, as we have seen in previous tutorials that a try-catch block is sufficient
for exception handling, however if you place a finally block then it will always run after the execution
of try block.
3. In normal case when there is no exception in try block then the finally block is executed after try
block. However if an exception occurs then the catch block is executed before finally block.
4. An exception in the finally block, behaves exactly like any other exception.
5. The statements present in the finally block execute even if the try block contains control transfer
statements like return, break or continue. Let’s see an example to see how finally works when return
statement is present in try block:
You can see that even though we have return statement in the method, the finally block still runs.
class JavaFinally
{
public static void main(String args[])
{
System.out.println(JavaFinally.myMethod());
}
4|P ag e
Object Oriented Programming
Exceptions Handling
The circumstances that prevent execution of the code in a finally block are:
– The death of a Thread
– Using of the System. exit() method.
– Due to an exception arising in the finally block.
close() statement is used to close all the open streams in a program. Its a good practice to use close()
inside finally block. Since finally block executes even if exception occurs so you can be sure that all
input and output streams are closed properly regardless of whether the exception occurs or not.
For example:
....
try{
OutputStream osf = new FileOutputStream( "filename" );
OutputStream osb = new BufferedOutputStream(opf);
ObjectOutput op = new ObjectOutputStream(osb);
try{
output.writeObject(writableObject);
}
finally{
op.close();
}
}
catch(IOException e1){
System.out.println(e1);
}
...
Finally block without catch
A try-finally block is possible without catch block. Which means a try block can be used with finally
without having a catch block.
5|P ag e
Object Oriented Programming
Exceptions Handling
...
InputStream input = null;
try {
input = new FileInputStream("inputfile.txt");
}
finally {
if (input != null) {
try {
in.close();
}catch (IOException exp) {
System.out.println(exp);
}
}
}
...
Finally block and System.exit()
System.exit() statement behaves differently than return statement. Unlike return statement
whenever System.exit() gets called in try block then Finally block doesn’t execute. Here is a code
snippet that demonstrate the same:
....
try {
//try block
System.out.println("Inside try block");
System.exit(0)
}
catch (Exception exp) {
System.out.println(exp);
}
finally {
System.out.println("Java finally block");
}
....
In the above example if the System.exit(0) gets called without any exception then finally won’t
execute. However if any exception occurs while calling System.exit(0) then finally block will be
executed.
try-catch-finally block
Either a try statement should be associated with a catch block or with finally.
Since catch performs exception handling and finally performs the cleanup, the best approach
is to use both of them.
Syntax:
try {
//statements that may cause an exception
}
catch (…) {
//error handling code
}
finally {
//statements to be executed
}
6|P ag e
Object Oriented Programming
Exceptions Handling
Example 1: The following example demonstrate the working of finally block when no exception occurs
in try block
class Example1{
public static void main(String args[]){
try{
System.out.println("First statement of try block");
int num=45/3;
System.out.println(num);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("ArrayIndexOutOfBoundsException");
}
finally{
System.out.println("finally block");
}
System.out.println("Out of try-catch-finally block");
}
}
Output:
class Example2{
public static void main(String args[]){
try{
System.out.println("First statement of try block");
int num=45/0;
System.out.println(num);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("ArrayIndexOutOfBoundsException");
}
finally{
System.out.println("finally block");
}
System.out.println("Out of try-catch-finally block");
}
}
Output:
7|P ag e
Object Oriented Programming
Exceptions Handling
Example 3: When exception occurs in try block and handled properly in catch block
class Example3{
public static void main(String args[]){
try{
System.out.println("First statement of try block");
int num=45/0;
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("ArithmeticException");
}
finally{
System.out.println("finally block");
}
System.out.println("Out of try-catch-finally block");
}
}
Output:
Sources:
8|P ag e