Exception Handling in Java

Exception Handling is one of the most important concept in Java for building better applications. In this chapter, we will walk you through some important and must know points about Exception Handling.

try-catch

class Innoskrit {
    public static void main( String args[] ) {
            
        try {
            // exception thrown here
        } catch(Exception e) {
            // exception caught here  
        }

    }
}

If a developer thinks that some part of the code may cause exception in the future that part of the code should be put inside the try block and has to be caught inside catch block.

Nested try-catch

class Innoskrit {
    public static void main( String args[] ) {
        int a = 5;
        int b = 0;

        try {
            try {
                a = a / b;
            } catch(ArithmeticException e) {
                System.out.print("B");
            }
        } catch(ArithmeticException e) {
            System.out.print("A");
        }
    }
}
class Innoskrit {
    public static void main( String args[] ) {
        int a = 5;
        int b = 0;

        try {
            try {
                a = a / b;
            } finally {
                System.out.print("B");
            }
        } catch(ArithmeticException e) {
            System.out.print("A");
        }
    }
}

If we have an exception in our program, it has to be caught at-most once for a try block.
For 1st code snippet, when ArithmeticException occurs in try block due to 5/0, control moves to the nearest catch block for a try block to handle the exception. So, this exception has been handled with inner catch block and hence, outer block will not get executed.
For 2nd code snippet, when ArithmeticException occurs there is no catch block for the inner try block and that’s why control will move to the outer catch block to handle the exception.

finally block

  • try block cannot exists alone, it should either be followed by finally block or catch block or both.
class Innoskrit {
    public static void main( String args[] ) {
            
        try {
            // exception thrown here
        } catch(Exception e) {
            // exception caught here  
        }

    }
}
class Innoskrit {
    public static void main( String args[] ) {
            
        try {
            // exception thrown here
        } finally {
            // mandatory, catch block absent 
        }

    }
}
  • For a try block, there can be only one finally block.
// correct
class Innoskrit {
    public static void main( String args[] ) {
            
        try {
        
        } catch(Exception e) { 
         
        } finally {
        
        }
        
    }
}
// incorrect
class Innoskrit {
    public static void main( String args[] ) {
            
        try {
        
        } catch(Exception e) { 
         
        } finally {
        
        } finally {
        
        }
        
    }
}
  • finally block is always executed whether the exception is handled or not, hence it is used for specific tasks like closing some connections or releasing resources at the end.
  • finally will still be executed if there is a return statement in the catch clause.

try-catch-finally

// correct
class Innoskrit {
    public static void main( String args[] ) {
            
        try {
        
        } catch(Exception e) { 
         
        } finally {
        
        }
        
    }
}
// incorrect
class Innoskrit {
    public static void main( String args[] ) {
            
        try {
        
        } finally {
        
        } catch(Exception e) { 
         
        } 
      
    }
}

Are multiple catch blocks allowed for a try block?

Yes, it is allowed. Let’s understand how?

class Innoskrit {
    public static void main( String args[] ) {
            
        try {
        
        } catch(Exception e) { 
         
        } catch(ArithmeticException e) { 
         
        } catch(NullPointerException e) { 
         
        }
        
    }
}

Every time an exception will be thrown by try block, it will be handled by first catch block because Exception is the parent class of ArithmeticException and NullPointerException. So, the last two catch statements will become unreachable and Hence, Compilation error.

class Innoskrit {
    public static void main( String args[] ) {
            
        try {
        
        } catch(ArithmeticException e) { 
         
        } catch(NullPointerException e) { 
         
        } catch(Exception e) { 
         
        }
        
    }
}

If no specific catch block is present to handle an exception, it will be handled by last catch block.

From the above two observations, we can conclude that the order of exceptions having an IS-A relation in multiple catch clauses needs to follow a bottom-up hierarchy (Child to Parent).

Can a catch block be written to handle multiple Exceptions?

Yes using pipe (|) operator, But the classes cannot be related, there should not be any IS-A (parent-child) relationship amongst the exceptions.

catch(ArithmeticException | NullPointerException | Exception e)  

The above catch block will always results in true as there is parent exception class in catch which will always catch an exception.
Hence, this will give us a compilation error.

catch(ArithmeticException | NullPointerExceptio e)  

The above line of code is absolutely correct as there is no IS-A relationship between both the classes.

Difference between throw and throws:

throwthrows
throw new IOException();int method() throws IOException, ArithmaticException {
}
throw is a statement and used inside the method definition or block.throws is used with the method signature.
It is used to throw one exception at a time.It can be used to throw multiple exceptions at a time.
throw v/s throws

Exception with Classes:

// correct
class Parent {
    void func() throws Exception {

    }
}

class Child extends Parent {
    void func() throws ArithmeticException {

    }
}
// incorrect
class Parent {
    void func() throws ArithmeticException {

    }
}

class Child extends Parent {
    void func() throws Exception {

    }
}

When there is inheritence in the code and parent class method throws some exception, then overridden method in the child class can either throw same exception or sub-class of that exception.

Innoskrit

Innoskrit

We're building a next-level EdTech Startup.

Related Posts

Leave A Reply

Your email address will not be published.