☰ Topics

Exception Handling

There are two types of errors: Compile-time errors and Run-time errors. To remove compile-time error, compiler is best. Exception handling is a mechanism to handle run-time errors (logical errors). Exception is an event that disrupts the normal flow of diagram. It is an object thrown at run-time. Exception handling upto some extent makes our program robust (error free). The root class of java is object class and the root class in error handling is throwable. The only disadvantage of this is the more the exception is used the slower the program gets. There are two types of exceptions given as follows:

Types of Exception:-

  1. Checked exception:- Checked Exceptions are also known as pre-checked exception. These are pre-defined exceptions of Java and it handles the critical exceptions by itself. If checked exceptions are not handled, i.e written in try-catch block the program won't be compiled.
  2. Unchecked exception:-The classes that extend RuntimeException are known as unchecked exception. These are not checked at compile-time rather they are checked at run-time. These are user handled exceptions such as Arithmetic Exception, NullPointer Exception, etc.
Advantages of Exception Handling:- The core advantage of exception handling is to maintain the normal flow of the application. Exception normally disrupts the normal flow of the application.


Ways of handling Exceptions

  1. try-catch & finally block:- Java try block is used to enclose the code that might throw an exception. It throws the exception to the catch block when there is no error, the control doesn't transfer to the catch block. Here, throw keyword is internally called for throwing the error.

    Life cycle of try block:
    
    1. try{}
       catch(Exception_class_name ref){}
    
    2. try{}
       finally{}
    
    3.try{
        #error code
      }
      catch(Exception_class_name ref){
        #Exception msg
      }
      finally{
        optional
      }
    

    There are 3 life cycle of the try catch and finally block:

    In first case, if an error occurs, then code after error won't be executed. The try block throws an exception and the control goes to catch block & the error is handled in catch block. If finally{} is not written then codes after catch{} will be executed.

    In second case, everytime try{} is executed, that many times finally{} will be executed.

    And in the last case, when try{} is executed and it throws exception to catch{}, then after executing catch{}, finally{} will be executed.

    Why we use finally{} ? Java finally block is optional and is used when it is needed. It is always executed whether exception is handled or not. There can be 10 lines of code in try block and an exception occurs on 6th line and then it is handled and cursor goes out of the loops, not completely executing try block and important line after exception is missed. Then to execute important code finally block is used. The finally block must be followed by try or catch block. For each try block there can be zero or more catch blocks but only one finally block. It is mainly used to put "clean up" code such as closing a file, closing connection etc. We write all important code in finally. If you don't handle exception, before terminating the program, JVM executes finally block.

    Example:-
    class Check{
        public static void main(String[] args){
            int a=10, b=0,c;
            try{
                c=a/b;
            }
            catch(Exception ex){
                System.out.println(ex.toString());
            }
            finally{
                System.out.println("Program executed");
            } 
        }
    }
    
    OUTPUT:-
        
    java.lang.ArithmeticException:  /by zero
    Program executed
    

  2. Multiple catch{} block:- One try{} block can have multiple catch{} block. When there are 3 lines in try{} each of which can generate interrupts, then 3 exceptions may be generated and for handling 3 exceptions we can write 3 catch{}. But when we are using root class of exception, then there is no need of writing multiple catch block. At a time only one exception is occured & at a time only one catch block is executed. All catch blocks must be ordered in the sequence of occurence of the exception. Multiple catch blocks helps in the faster execution of the codes.

      try{
        #error code
      }
      catch(ArithmeticException ex){
        #Exception msg
      }
      catch(FileNotFoundException ex){
        #Exception msg
      }
      catch(ArrayIndexOutOfBoundException ex){
        #Exception msg
      }
      catch(Exception ex){
        #Exception msg
      }
    

  3. Nested try{} block:- The try block within a try block is known as nested try block. Sometimes a situation may arise where a part of a block may cause one error & the entire block itself may cause another error. In such cases, exception handlers have to be nested. But it should have a consecutive catch block. In this method complexity increases.

            try{
               #statements;
               try{
                 statement1;
               }
               catch(Exception ex){
               }
            }
            catch (Exception ex){
            }
        

  4. throws keyword:- It is used for checked exception. There is no try-catch{} block in it. It can used only with main(). It is also used to declare more than one exceptions at a time by separating them with comma(,).

                public static void main(String[] args) throws ArithmeticException, FileNotFoundException
                {
                  #statements;
                }