Exception Handling snippet – try, catch, finally (Java)
April 27, 2016
Categorised in: Java Codes
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
Pratik Kataria is currently learning Springboot and Hibernate.
Technologies known and worked on: C/C++, Java, Python, JavaScript, HTML, CSS, WordPress, Angular, Ionic, MongoDB, SQL and Android.
Softwares known and worked on: Adobe Photoshop, Adobe Illustrator and Adobe After Effects.