info@tutsfinder.in



Exception Handling

What is Exception?

Exception is an event that occurs during an execution of a program that disrupts the normal flow the program.

To handle these exceptions, there be a concept in java that is Exception handling; it maintains the normal flow of the program.


Main advantage of exception handling is that it’s maintain the normal flow of the program and Separate error handling code form normal code.

Exception can be occurred due to wrong input data e.g. divide by zero.


Types of Exceptions —

• Checked exceptions — All exceptions except runtime exceptions are checked exceptions.

• Unchecked exceptions — All runtime exceptions are unchecked exceptions.

• Errors — Errors are not recoverable.


Try / catch block

Error prone code is placed in try block and catch block is used to handle that error, try block should be always followed by catch or finally block.


Syntax: 
try{
//error prone code
} 
Catch(Exception name xyz){
//catch block
}


Finally

In this block, we placed important code that should be executed whether the exception is handled or not.


Syntax: 
try{
//error prone code
} 
Finally{
}
	


Throw

Throw keyword that allows the user to throw an exception or any class that implements “throwable” exception.

Throws

A java keyword used in method declarations that specify which exceptions are not handled within the method but rather passed through the next higher level of the program.

A basic Program to show how try/catch block works.

In this example, we have divided the no. by zero and it gives an error.

public class TryCatchExample {  
  
    public static void main(String[] args) {  
        try  
        {  
        int number=10/0;   
        }  
              
        catch(Exception e)  
        {  
                   
            System.out.println("Number can't divided by zero.");  
        }  
    }  
      
}  
	


Output:
Number can't divided by zero.


Program to show how finally block executes.

Here in try block we placed a error prone code and handle in catch block and in finally block we placed our rest code.


public class FinallyBlock{  
  public static void main(String args[]){  
  try{  
   int number=10/0;  
   System.out.println(number);  
  }  
  catch(ArithmeticException e){
	System.out.println(e);
	}  
  finally{
	System.out.println("Finally Block is always executed either error is caught or not.");
	}  
  System.out.println(" Output is: " + 10/10);  
  }  
}  
	


Output:
java.lang.ArithmeticException: / by zero
Finally Block is always executed either error is caught or not.
 Output is: 1


Program to show how throw keyword works.

class JavaThrow 
{ 
  
    public static void main(String args[]) 
    { 
        try
        { 
            throw new NullPointerException("Example");
        } 
        catch(NullPointerException e) 
        { 
            System.out.println("Exception in main caught."); 
        } 
    } 
}  
	


Output:
Exception in main caught.