Thursday, 27 September 2018

Checked vs Unchecked Exception in Java

Checked and Unchecked exceptions are part of the Exception Handling in Java.

 


What are checked exceptions?

Ans : Checked exceptions are checked at the compile-time.

 

What do you mean by above line ? 

What kind of exceptions are checked by compiler ?

   

All the checked exceptions are part of Exception class.


Below are few checked exceptions :


CloneNotSupportedException
ClassNotFountException
IOException (subclass of IOException  : FileNotFoundException )
ParseException
InterruptedException
SQLException

 

There are many scenario where compiler knows very well the code may throw exception so it must be checked during compile time or in other words the code must be written inside try/catch block or it should declare the exception using throws keyword. If we fail to do that then it will throw compile time error.

 

Lets see one example for checked exception.

 

Below is the program without try/catch. This will throw compile time error as here we are doing IO operation and compiler mandate to handle IOException using try-catch or throws.


import java.io.FileOutputStream; 
public class FileOutputStreamExample { 
        public static void main(String args[]){   
   
                 FileOutputStream fout=new 

                 FileOutputStream("D:\\TextFile.txt");   
                 String s="Welcome to FileHandling program.";   
                 byte b[]=s.getBytes();//converting string into byte array   
                 fout.write(b);   
                 fout.close();   
                 System.out.println("success...");   
                   
          }   
    }  

 

OUTPUT :

 

Exception in thread "main" java.lang.Error: Unresolved compilation problems:
    Unhandled exception type FileNotFoundException
    Unhandled exception type IOException
    Unhandled exception type IOException

    at FileOutputStreamExample.main(FileOutputStreamExample.java:5)

 

 

Note : Since we didn’t handled/declared the exceptions, above program gave the compilation error.

 

Same program with proper exception handling :


import java.io.FileOutputStream; 
import java.io.IOException;
public class FileOutputStreamExample { 
        public static void main(String args[]){   
          try{   
                 FileOutputStream fout=new

                 FileOutputStream("D:\\TextFile.txt");   
                 String s="Welcome to FileHandling program.";   
                 byte b[]=s.getBytes();//converting string into byte array   
                 fout.write(b);   
                 fout.close();   
                 System.out.println("success...");   
                }catch(IOException e){System.out.println(e);}   
          }   
    } 

 

OUTPUT :

success...

 

What are Unchecked checked exceptions?

 

Ans : Unchecked exceptions are not checked at the compile-time.

 

Here compiler cannot estimate what kind of exception going to occur and so it doesn't force you to keep try/catch or throws. It is up to the programmer to judge the conditions in advance and handle them appropriately.

 

All Unchecked exception are part for RuntimeException class.

 

Below are few Unchecked exceptions :
 

ArithmeticExeception
NumberFormatException
NullPointerException
ArrayIndexOutOfBoundException
ClassCastException

 

Example 1 : In this example we are not handling exception and also compiler doesn't force to keep try/catch as mathematical operation is done during runtime.


public class O {

    public static void main(String[] args) {
       
        System.out.println("main begin");
   
            System.out.println(1);
            int i = 10 / 0;
            System.out.println(2);
       
            System.out.println(3);
       
       
        System.out.println("main end");
    }

 

OUTPUT :

 

main begin
1

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at O.main(O.java:15)

 

Note : This kind of exceptions are more dangerous as it occur during runtime so you have to judge and keep try-catch or throws accordingly.


Example 2 : In this example we are handling Runtime Exception.

 

public class O {

    public static void main(String[] args) {
  
      System.out.println("main begin");
   
        try {
            System.out.println(1);
            int i = 10 / 0;
            System.out.println(2);
        }
       
        catch (ArithmeticException ex) {
           
            System.out.println(3);
        }
       
        System.out.println("main end");
    }

   
}

 OUTPUT :


main begin
1
3
main end


Other then above all runtime exceptions, all the Error are also unchecked as this also occur duirng runtime. Error occurs due to some external environment and it occurs at runtime like StackOverflowError.

If there is no space for a new stack frame then, the StackOverflowError is thrown by the Java Virtual Machine (JVM).

For example : 

StackOverflowError
OutOfMemoryError
NoClassDefFoundError
NoSuchMethodError
AssertionError

No comments:

Post a Comment