Exception Handling Example Java Program


Definition

Exception handling is the process of responding to the occurrence, during computation, of exceptions ? anomalous or exceptional conditions requiring special processing ? often changing the normal flow of program execution. It is provided by specialized programming language constructs or computer hardware mechanisms.

Syntax

try{
	//Statements
	}catch(Expression_type Variable_name){
		//Statements
	}

Exception Handling Example Program

class ExceptionHandlingExample{
	public static void main(String[] args){
		int num1,num2,num3;
		num1=20;
		num2=0;
		try{
			num3=num1/num2;
			System.out.println("Result is "+num3);
		}catch(ArithmeticException ae){
				System.out.println("Numbers cannot be divided by zero");
			}
	num3=num1+num2;
	System.out.println("Result after addition is "+num3);
	}
}	

Sample Output

Output is:
Numbers cannot be divided by zero
Result after addition is 20