BIG
DATA

JAVA

Exception handling in Java

Read more about »
  • Java 9 features
  • Read about Hadoop
  • Read about Storm
  • Read about Storm
 

Exception propagation

An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method,If not caught there, the exception again drops down to the previous method, and so on until they are caught or until they reach the very bottom of the call stack.This is called exception propagation.

Unchecked Exception propagation

class JavaExceptionPropagation{

	public static void main(String args[]){
		JavaExceptionPropagation obj=new JavaExceptionPropagation();
		obj.method1();
		System.out.println("Normal code execution flow continues...");
	}

	void method1(){
		try{
			method2();
		} catch(Exception e){
			System.out.println("Exception handling is done here");
		}
	}

	void method2(){
		method3();
	}

	void method3(){
		int out = 50 / 0;  //Exception occurs here
	}
}

Output :

Exception handling is done here
Normal code execution flow continues...

Checked Exception propagation

class JavaExceptionPropagation{

	public static void main(String args[]){
		JavaExceptionPropagation obj=new JavaExceptionPropagation();
		obj.method1();
		System.out.println("Normal code execution flow continues...");
	}

	void method1(){
		try{
			method2();
		} catch(Exception e){
			System.out.println("Exception handling is done here");
		}
	}

	void method2(){
		method3();
	}

	void method3(){
		throw new java.io.IOException("Some IO Exception..");
	}
}

Output :

Compile Time Error