Saturday, July 28, 2012

Checked vs Unchecked exceptions





  • Exception subclasses represent errors that a program can reasonably recover from. Except for RuntimeException and its subclasses (see below), they generally represent errors that a program will expect to occur in the normal course of duty: for example, network connection errors and filing system errors.
  • Error subclasses represent "serious" errors that a program generally shouldn't expect to catch and recover from. These include conditions such as an expected class file being missing, or an OutOfMemoryError.
  • RuntimeException is a further subclass of ExceptionRuntimeException and its subclasses are slightly different: they represent exceptions that a program shouldn't generally expect to occur, but could potentially recover from. They represent what are likely to be programming errors rather than errors due to invalid user input or a badly configured environment.

Unchecked exceptions:
·       ·        Represent defects in the program (bugs) - often invalid arguments passed to a non-private method. "Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program's logic and cannot be reasonably recovered from at run time."

·      They DON'T have to be caught or declared thrown.

·     They are subclasses of java.lang.RuntimeException, and are usually implemented using IllegalArgumentException, NullPointerException, or IllegalStateException

·        A method is not obliged to establish a policy for the unchecked exceptions thrown by its implementation (and they almost always do not do so)


Checked exceptions:
·        Represent invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files)
·        Checked exceptions must be explicitly caught or propagated as described in Basic try-catch-finally Exception Handling.
·        They are subclasses of java.lang.Exception
·        A method is obliged to establish a policy for all checked exceptions thrown by its implementation (either pass the checked exception further up the stack, or handle it somehow)
·        It is somewhat confusing, but note as well that RuntimeException (unchecked) is itself a subclass of Exception (checked).



List of Checked Exceptions-
Following are the list of various checked exception that defined in the java. lang package.
   Exception
   Reason for Exception
 ClassNotFoundException
This Exception occurs when Java run-time system fail to find the specified class mentioned in the program
Instantiation Exception
This Exception occurs when you create an object of an abstract class and interface
Illegal Access Exception
This Exception occurs when you create an object of an abstract class and interface
Not Such Method Exception
This Exception occurs when the method you call does not exist in class

2. Unchecked Exception:- These Exception arises during run-time ,that occur due to invalid argument passed to  method. The java Compiler does not check the program error during compilation. For Example when you divide a number by zero, run-time exception is raised.
  Exception
    Reason for Exception
Arithmetic Exception
These  Exception occurs, when you divide a number by zero causes an  Arithmetic Exception
Class Cast Exception
These Exception occurs, when you try to assign a reference variable of a class to an incompatible reference variable of another class
Array Store Exception
These Exception occurs, when you assign an array which is not compatible with the data type of that array
Array Index Out Of Bounds Exception
These Exception occurs, when you assign an array which is not compatible with the data type of that array
Null Pointer Exception
These Exception occurs, when you try to implement an application without referencing the object and allocating to a memory
Number Format Exception
These Exception occurs, when you try to convert a string variable in an incorrect format  to integer (numeric format) that is not compatible  with each other
Negative ArraySizeException
These are Exception, when you declare an array of negative size.




Rule of thumb:

Unchecked exceptions occur when there are logic errors with your program. Things that you as a programmer got wrong, and are able to fix in your own code (like dividing by zero, or going out of bounds on an array).

Checked exceptions come up when there are things that can go wrong that you can't control, like opening a file that doesn't exist, or making a connection to a server that isn't responding, etc.

 --------------------------------------------------------------------------

Exception Propagation 


               Method call stack

ExceptionDemo.method4  <--- Exception occurs
     ExceptionDemo.method3
     ExceptionDemo.method2
     ExceptionDemo.method1
     ExceptionDemo.main


 If not handled in any method, the exception is thrown and the application will stop



public class ExceptionDemo {
    
     public void method4(){
          int a=7;
          int b=0;
          int c=a/b;
     }
    
     public void method3(){
          this.method4();
          System.out.println("After method 4 completion");
     }

     public void method2(){
          this.method3();
          System.out.println("After method 3 completion");
     }
    
     public void method1(){
          this.method2();
          System.out.println("After method 2 completion");
     }

public static void main(String[] args){

     ExceptionDemo ex = new ExceptionDemo();
     ex.method1();
     System.out.println("After method 1 completion");
}   
}

Exception in thread "main" java.lang.ArithmeticException: / by zero
     at ExceptionDemo.method4(ExceptionDemo.java:7)
     at ExceptionDemo.method3(ExceptionDemo.java:11)
     at ExceptionDemo.method2(ExceptionDemo.java:16)
     at ExceptionDemo.method1(ExceptionDemo.java:22)
     at ExceptionDemo.main(ExceptionDemo.java:34)


-------------------------------------------------------------------------------------------------


public class ExceptionDemo {
    
     public void method4(){
          int a=7;
          int b=0;
          int c=a/b;
     }
    
     public void method3(){
          this.method4();
          System.out.println("After method 4 completion");
     }

     public void method2(){
          this.method3();
          System.out.println("After method 3 completion");
     }
    
     public void method1(){
          try{
              this.method2();
              System.out.println("After method 2 completion");
          }
          catch(Exception e)
          {
              System.out.println(e.getMessage());
          }
     }

public static void main(String[] args){

     ExceptionDemo ex = new ExceptionDemo();
     ex.method1();
     System.out.println("After method 1 completion");
}   
}

/ by zero
After method 1 completion
-----------------------------------------

            

              Writing own exception




public class MyCheckedException extends Exception{
    public MyCheckedException(String msg){
      super(msg);
    }

    public MyCheckedException(String msg, Throwable t){
      super(msg,t);
    }
}


No comments:

Post a Comment