Skip to content

Module 2: Exceptions

Rishabh Malviya edited this page Feb 7, 2023 · 1 revision

Exception Handling

Using Try-Catch and Try-with-Resource

Try-Catch

  • Try Catch is used to handle exceptions in Java.
  • Every exception is an object of a class called Exception that extends the Throwable class.
  • The try block contains the code that might throw an exception. The catch block contains the code that handles the exception.
  • The finally block contains the code that will be executed whether an exception is thrown or not.
class Main{
    Throwable t = new Throwable();
    public static void main(String[] args){
        try{
            throw new Exception();
        }catch(Exception e){
            System.out.println("Exception");
        }finally{
            System.out.println("Finally");
        }
    }
}
// Output: Exception
//         Finally

Try-with-Resource

  • The try-with-resource statement is a try statement that declares one or more resources.
  • A resource is an object that must be closed after the program is finished with it.
  • The try-with-resource statement ensures that each resource is closed at the end of the statement.
class Main{
    public static void main(String[] args){
        try(FileInputStream file = new FileInputStream("resource.txt")){ // file is a resource
            while(file.readLine() != null){
                System.out.println(file.readLine());
            }
        }catch(Exception e){
            System.out.print(e.getMessage());
        }
    }
}

Finally

  • The finally block is used to execute important code such as closing connection, streams etc.
  • The finally block is always executed whether an exception is handled or not.
class Main{
public static void main(String[] args){
        try{
            System.out.println("I am Try"); // It will try to execute
        }catch(Exception e){
            System.out.println("I am Catch");  // It will execute only when exception is thrown
        }finally{
            System.out.println("I am Finally"); // It will always execute
        }
    }
}
// Output: Try
//         Finally

Exception Hierarchy

  • The Throwable class is the root of the Java exception hierarchy.
  • The Exception class and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.
  • The Error class and its subclasses are a form of Throwable that indicates serious problems that a reasonable application should not try to catch.
  • The RuntimeException and its subclasses are a form of Exception that indicates conditions that a reasonable application might want to catch.
  • The Exception class and any subclasses that are not also subclasses of RuntimeException are checked exceptions.

Clone this wiki locally