Exception handling mechanism

Exception handling mechanism is a way to handle the exception occur in your program. Using the try/catch block we can handle exception.

Exception handling mechanism

Exception handling mechanism is a way to handle the exception occur in your program. Using the try/catch block we can handle exception.

Exception handling mechanism

Exception handling mechanism

In this tutorial you will learn about exception handling mechanism in java. Exception means error in your program. Exception handling mechanism is a way to handle the exception in your program. Using three keywords you can handle exception in java they are as follows:

  • try
  • catch
  • finally

Through these three keywords you can handle your exception occur in your program.

try block

The code which might throw an exception are enclosed within the try block. It is used within the method which might throw an exception, but try block must followed by catch or finally.

Syntax :  

  try {
          statement;
    } catch(Exception-class-name ob){}

catch block :

catch block is used to handle the exception.and it must be followed try block.

Example :  Code without using exception handling mechanism

public class Exception {
     public static void main(String args[])
	{
		int result=10/0;
		System.out.println("Result = "+result);
	}
 }

If you compile and execute the program it will throw an arithmetic exception "divide by zero" like as the output below:

Download SourceCode

If the same code will be written using try/catch block then the code will be as follows:

public class Exception {
     public static void main(String args[])
	{
		try{
			int result=10/0;
		}catch(ArithmeticException ex){
			System.out.println(" ");
			System.out.println("Exception handled " +ex);}
		}
     }

After compiling and executing the program the output will be as follows:

Download Source Code

finally block

finally block is a block which is always executed whether exception occurred or not in the code. The finally block is always followed by try block. finally block is mainly used for closing connection or clean type of statement and finally block will always after catch block the syntax is as follows:

try
 {
  //code
    }catch(Exceptiontype ob){}
   finally
   {
    //statement;
   }

Example : A simple program using finally

public class Exception {
     public static void main(String args[])
	{
		try{
			int result=10/2;
			System.out.println("The value of result is = " +result);
		}catch(ArithmeticException ex){
			System.out.println("Exception handled " +ex);}
		 finally
		 {
			 System.out.println("Always executed");
		 }
	        System.out.println("rest code ");	
	  }
    }

Output of the program :

Download SourceCode