Please disable adblock to view this page.

← Go home

Exception Handling snippet – try, catch, finally (Java)

April 27, 2016
Published By : Pratik Kataria
Categorised in:

public class Main {
	//Keywords : Try, catch, finally, throw, throws
	public static void main(String[] args) {
		
		//Throwable class is base for Class of Errors and 
		//Class of Exception. Then in Exception class you have specific classes
		//like arrayoutofbound i.e. they are derived classes
		
		try{
		
			int a = 10;
			int b = 0;
			
			int c = a/b; //Code will crash here so further statements won't be executed
			
			System.out.println(c);
			
			int arr [] = {1,2,3,4};
			
			System.out.println(arr[1]);

			System.out.println(arr[4]);
			
		}
		catch(ArrayIndexOutOfBoundsException e){
			System.out.println("You are crossing the limit where no value exists\n\n");
		}
		catch (ArithmeticException e) {
			System.out.println("Aw, sorry you can't divide by 0. Please contact Arryabhatta for more details πŸ™‚ \n\n");
		
		}
		catch(Exception e){	//This general block should always be last after specific catch blocks
			e.printStackTrace();
		}
		finally{
			System.out.println("Program crashed but I still execute. #ThugLife");
		}
		
	}
	
}

Output:

Aw, sorry you can’t divide by 0. Please contact Arryabhatta for more details πŸ™‚
Program crashed but I still execute. #ThugLife

View Article Page
Download

Pratik Kataria is a budding programmer, web designer and developer.