• Multiple Exceptions’ handling and workflow • Best Practices for Exception Handling
Practice Task # 1 - Java try-catch block
public class TryCatchExample3 {
public static void main(String[] args) {
try { int data=50/0; //may throw exception // if exception occurs, the remaining statement will not exceute System.out.println("rest of the code"); } // handling the exception catch(ArithmeticException e) { System.out.println(e); } } }
Practice Task # 2 - Java Catch Multiple Exceptions
public class MultipleCatchBlock1 { public static void main(String[] args) { try{ int a[]=new int[5]; a[5]=30/0; } catch(ArithmeticException e) { System.out.println("Arithmetic Exception occurs"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBounds Exception occurs"); } catch(Exception e) { System.out.println("Parent Exception occurs"); } System.out.println("rest of the code"); } }
Practice Task # 3 - Java finally block
public class TestFinallyBlock1{ public static void main(String args[]){
try {
System.out.println("Inside the try block");
//below code throws divide by zero exception
int data=25/0; System.out.println(data); } //cannot handle Arithmetic type exception //can only accept Null Pointer type exception catch(NullPointerException e){ System.out.println(e); }
//executes regardless of exception occured or not
finally { System.out.println("finally block is always executed"); }
System.out.println("rest of the code...");
} }
Practice Task # 4 - Java throw Exception
public class TestThrow1 { //function to check if person is eligible to vote or not public static void validate(int age) { if(age<18) { //throw Arithmetic exception if not eligible to vote throw new ArithmeticException("Person is not eligible to vote"); } else { System.out.println("Person is eligible to vote!!"); } } //main method public static void main(String args[]){ //calling the function validate(13); System.out.println("rest of the code..."); } }