Exception Handling in Java

0
103

An exception is any sort of deviation from what we a program is expecting. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore these exceptions needs to be handled.

The following is an array is declared with 2 elements. Then the code tries to access the 3rd element of the array which throws an exception.

[java] import java.io.*;
public class ExceptionDemo{

public static void main(String args[]){
try{
int a[] = new int[2];
System.out.println(“Access element three :” + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println(“Exception thrown :” + e);
}
System.out.println(“Out of the block”);
}
}

[/java]

A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following:

[java]

try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}
[/java]

The finally block

The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception.

Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.

A finally block appears at the end of the catch blocks and has the following syntax:

[java]

try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}

[/java]
Facebook Comments

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.