Thursday 27 February 2014

checked vs unchecked Exceptions

1. Checked exceptions are those which are checked at compile time, Unchecked exceptions are not checked at compile time and raised at run time.

2. In Java, Error, RuntimeExceptions and its subclasses comes under unchecked exceptions category, where as Exception and its sub classes comes under checked exceptions category.

3. Checked exceptions are subject to catch/specify requirement.

For Example, see the below program,

import java.io.*;

class CheckedEx{
 public static void main(String args[]){
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  System.out.println("Enter your name ");
  String name = br.readLine();
  System.out.println("Hi " + name);
 }
}
   
br.readLine(), throws IOException, which is a checked exception, so compiler checks whether the program handles it or not, If the program is not handling then compiler throws the error. Above program is not handling the cecked Exception (IOException), so compiler throws the below error.

CheckedEx.java:7: error: unreported exception IOException; must be caught or declared to be thrown
String name = br.readLine();
^
1 error

To make the program compile and runs fine, There are two options

Option 1: program can handle the IOException.
import java.io.*;

class CheckedEx{
 public static void main(String args[]){
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  try{
   System.out.println("Enter your name ");
   String name = br.readLine();
   System.out.println("Hi " + name);
  }
  catch(IOException e){
   System.out.println(e);
  }
 }
}

Output
Enter your name
abc
Hi abc

Option 2: program can throws the IOException.
import java.io.*;

class CheckedEx{
 public static void main(String args[]) throws IOException{
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  System.out.println("Enter your name ");
  String name = br.readLine();
  System.out.println("Hi " + name);
 }
}

Output
Enter your name
abc
Hi abc

4. Program can handle and recover from checked exceptions, Of course from RuntimeException recovery is possible. Error are special category of unchecked exception, Where recovery from them is almost impossible.

5. Compiler throws an error, if the program tries to handle a checked exception, which will never occurs in the program.

import java.io.*;

class CheckedEx{
 public static void main(String args[]){
  try{
   int a = 10+20;
  }
  catch(IOException e){
  
  }
 }
}

When you tries to compile the above program, compiler throws the below error

CheckedEx.java:7: error: exception IOException is never thrown in body of corresponding try statement
catch(IOException e){
^
1 error

Custom Exceptions                                                 Overriding vs Exception Handling                                                 Home

No comments:

Post a Comment