Customized Exception Handling by try-catch

Customized Exception Handling by try-catch

 It is highly recommanded to handle exceptions.

The code may raised an exception is called risky code, and we have to define that code inside try block and corresponding handling code we have to define inside catch block.

Syntax -:

     try{
          // risky code
      }catch{
           // handling code
     }

example-:
without try-catch -:

class WithOutTryCatch{
      public static void main(String[] args){
              System.out.print("Statement 1");
              System.out.print(10/0);
               System.out.print("Statement 2");
      }
}

Output-:
    Statement 1
    RE : AE / by zero
    abnormal termenation

with try-catch-: 

 class CustmizeException{
      public static void main(String[] args){
             System.out.print("Statement 1");
             try{
              System.out.print(10/0);
            }catch(AirthmeticException ae){
                     System.out.print(10/2);
            }
          System.out.print("Statement 3");
      }
}

Output-:
    Statement 1
    5
    Statement 3

Control flow of try-catch-:


try{
   statement 1;
    statement 2;
    statement 3;
}catch(){
     statement 4;
}
statement 5;

case 1-:if raised exception on statement 2 then execution of programme
statement 1,statement 4,statement 5,normal execution

case 2-:if an exception raised on statement 2 and catch block not matched
   statement 1,abnormal execution  

case 3-:if an exception raised on statement 4 or statement 5 then it is always abnormal termination.

Note-:
    Within the try block if anywhere exception raised then rest of try block won't execute even though
we handle that exception. Hence, within the try block only risky code and length of try block should as less as possible.
    In addition to try block, there may be chance of raising an exception inside catch and finally blocks.
    If any statement which is not part of try block and raises exception then it is always abnormal termination.

Method to print exception information-: Throwable class defines the following methods to print exception information.
  1. printStackTrace()-: name of exception:description, stack trace.
  2. toString()-: Name of exception :description.
  3. getMessage()-: description only.
Example-:
class Test{
   public static void main(String[] args){
        try{
               System.out.print(10/0);
        }catch(ArithmeticException e){
                e.printStackTrace(); //1
                System.out.print(e); or System.out.print(e.toString());//2
                System.out.print(e.getMessage());//3
      }
    }
}

Output-:
             1-: java.lang.ArithmeticException: / by zero at Test main()
             2-: java.lang.ArithmeticException: / by zero
             3-:  / by zero


Note-: Internally, default exception handler will use print stack trace method to print exception information to the console.

Try with multiple catch blocks-:

The way of handling an exception is varied from exception to exception, hence every exception type it is highly recommanded to take separate catch block. That is, trying with multiple catch block is always possible and recommanded to use.

example-:

try{
       Risky code
}catch(ArithmeticException e){
        System.out.print(e.toString());
}catch(FileNotFoundException e){
           e.printStackTrace();
}catch(SQLException e){
    System.out.print(e.getMessage());
}catch(Exception e){
    default exception
}

order of catch blocks-:
If try with multiple catch blocks present then the order of catch blocks is very important we have to take child first and then parent otherwise we will get a compile time error saying exception xxx has already been caught.

example-:

Given that the `catch (Exception e)` block comes before the `catch (ArithmeticException e)` block, it will catch the `ArithmeticException` first. As a result, the second catch block (for `ArithmeticException`) will never be executed. The program will print the stack trace and related information for the `ArithmeticException` to the console due to the first catch block.

Not Allowed
 try{
          System.out.print(10/0);
}catch(Exception e){
    e.printStackTrace();
}catch(ArithmeticException e){
   e.printStackTrace();
}

compile time error-: Exception java.lang.ArithmeticException: has already been caught.

We can't declare two catch blocks for the same exception, otherwise we will get a compile time error.

In this code, the first `catch` block will catch the `ArithmeticException`, and the second one is redundant and will not be executed. The program will print the stack trace and related information for the `ArithmeticException` to the console.

Not Allowed
try{
          System.out.print(10/0);
}catch(ArithmeticException e){
    e.printStackTrace();
}catch(ArithmeticException e){
   e.printStackTrace();
}
compile time error-: Exception java.lang.ArithmeticException: has already been caught.




Allowed
try{
          System.out.print(10/0);
}catch(ArithmeticException e){
    e.printStackTrace();
}catch(Exception e){
   e.printStackTrace();
}
successfully compile