Catching and Handling Exceptions

The three exception handler components are used to catch and handle the exceptions. These are try, catch and finally clause.

Catching and Handling Exceptions

The three exception handler components are used to catch and handle the exceptions. These are try, catch and finally clause.

Catching and Handling Exceptions

Java Catching and Handling Exceptions

     

The various keywords for handling exceptions are below.

  • try

  • catch

  • finally

  • throw

  • throws

The three exception handler components are used to catch and handle the exceptions. These are try, catch and finally clause. The mechanism to catch an exception in Java is to use try and catch block. Every catch block can handle only one type of exception however you can use more than one catch clause in a single try block. Simply a statement is surrounded by the try block that may cause the exception to occur. Then the try block is followed by the catch block. And if the exception occurs then this catch block specifies a code that should be executed. 

Using try and catch:-

The syntax for the usage of try, catch and finally block is given below.

try{
       ???
       ???
}
catch(<exceptionclass1> <obj1>){
       ???
       ???
}
finally{
       ???
       ???

 

For using an exception handler in an application, the first step we need to do is to enclose the code that is likely to generate an exception inside a try block. If an exception occurs in the try block then it is handled by the exception handler associated with it. For doing this we need to have one or more catch blocks after the try block, where each catch block acts as an exception handler and can handle the type of exception indicated by its arguments.

 

Lets have a look at the example which shows the implementation of the try, catch and finally block. Here we have used "fis = new FileInputStream (new File (args[0]));" which throws an exception if we write a name of a file which doesn't exist as shown in the output.

 

import java.io.*;

class Test{
public static void main(String args[])throws IOException {
FileInputStream fis=null;
try{
fis = new FileInputStream (new File (args[0]));
}
catch (FileNotFoundException e){
System.out.println("File not found!");
}
finally{
fis.close();
}
}
}

Output of program:

C:\Roseindia\vinod\Exception>javac  Test.java

C:\Roseindia\vinod\Exception>java  Test
File not found!

Download this example

The code which is to be executed in a try block indicates that it will throw an exception. And if the exception occurs then the runtime system checks whether the exception thrown by try block matches to the one in catch clause or not. If yes, then the code within the catch clause gets executed which actually handles the exception. 

Using final: It is always a good practice to use finally clause after the try and catch block because the finally block always executes even if an unexpected exception occurs i.e. whether or not an exception thrown. The finally block executes if and only if the try block exits. Other than exception handling the finally clause helps you in avoiding any cleanup code accidentally bypassed by a return etc. The statements within the finally block gets executed by the the runtime system  without taking care of what happens within the try block.  

There are two steps to use the finally clause:

  • First, you need to enclose the code in a try block that has multiple exit points.

  • Secondly after the try block exits place the code that must be executed in a finally clause. 

Same way we have used the finally block which will execute after the try and catch block.

import java.io.*;

class Test{
public static void main(String args[]){
FileInputStream fis=null;
try {
fis = new FileInputStream (new File (args[0]));
int ch;
while ((ch = fis.read()) != -1){
System.out.print ((char) ch);
}
}
catch (FileNotFoundException e){
System.out.println("File not found!");
}
catch (IOException e){
System.out.println("Unable to read file!");
}
finally{
System.out.println();
System.out.println("In finally.");
try{
if(fis!=null){
fis.close();
}
}
catch (IOException ioe){
System.out.println("In finally.");
}
}
}
}

Output of program:

C:\Roseindia\vinod\Exception>javac  Test.java

C:\Roseindia\vinod\Exception>java  Test abc
File not found!

In finally.

Download this example

Using throws: The other way to handle an exception is using the throws clause. When you call a method from the java API that throws a checked exception, you must either throw the exception or catch it. If you decide that you can't handle the exception properly, then the exception can be declared to the method header using the throws keyword  followed by the class name of the exception. 

You might have come across the throws IOException clause in the method header. For example System.in.read() will give a compile error for IOException. Add the throws clause to the surrounding method to pass the error up to the next level (or else write your own catch/try handler). This clause is placed between the parameter list and the starting of the opening brace of the method. We use this clause when we know that a particular exception may occur. Then instead of terminating the program the compiler throws the exception.

While the throw keyword (note the singular form) is used to force an exception. It can also pass a custom message to your exception handling module. for example:-

throw new FileNotFoundException("Could not find books.txt");

The syntax for coding the throws clause of a method is as:-

method declaration throws Exception1,[Exception2] .......{ }

Likewise we have used throws clause to the method header as "throws FileNotFoundException,IOException " which throws an exception as shown in the output. 

import java.io.*;

class Test3{
public static void main(String args[]) throws FileNotFoundException,IOException {
FileInputStream fis=null;
fis = new FileInputStream (new File (args[0]));
int ch;
while ((ch = fis.read()) != -1){
System.out.print ((char) ch);
}
fis.close();
}
}

Output of program: 0

C:\Roseindia\vinod\Exception>javac  Test3.java

C:\Roseindia\vinod\Exception>java  Test3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Test3.main(Test3.java:6)

Download this example

  1