Organize Code

Execption

Java

 

Try Catch

Java 8
class Math{

  public void divide(int a, int b) {
    try {
      System.out.println(a/b);
    } catch(Exception e) {
      System.out.println("Cannot divide by zero");
    }
  }
  
}

Try/Catch blocks are used for handling exceptions and errors that can happen in runtime.

Put the risky part of the code inside the try block and specify what to do if an exception happens inside catch block.

 

Catch Specific Exception

Java 8
class Math{

  public void divide(int a, int b) {
    try {
      System.out.println(a/b);
    } catch(ArithmeticException e) {
      System.out.println("Cannot divide by zero");
    } catch(Exception e) {
      System.out.println(e.getMessage());
    }
  }
  
}

You can have multiple catch blocks for better error handling.

This helps to run different error handling blocks of code for different types of exceptions.

 

Caught Exception object

Java 8
class Math{

  public void divide(int a, int b) {
    try {
      System.out.println(a/b);
    } catch(Exception e) {
      System.out.println(e.getMessage());
      System.out.println(
        Arrays.toString(e.getStackTrace()));
    }
  }

}

Exception is the top level exception class in Java.

Exception class has 2 useful methods:

  • getMessage() - Exception message
  • getStackTrace() - Exception stack as array

In practice you should always try to create inherited classes from top level exceptions and throw those when you are writing your code.

 

Finally

Java 8
class Math{

  public void divide(int a, int b) {
    try {
      System.out.println(a/b);
    } catch(ArithmeticException e) {
      System.out.println("Cannot divide by zero");
    } catch(Exception e) {
      System.out.println("Some other error happened");
    } finally {
      System.out.println("divide method executed");
    }
  }
  
}

The code inside the finally block will always be executed after the Try/Catch block.

Even if you have a return statement inside a try or catch blocks, the finally block will be run before exiting the method.

 

Throw

Java 8
class Math{

  public void divide(int a, int b) {
    try {
      throw new Exception("Error for no reason");
    } catch(Exception e) {
      System.out.println("Executed all the time");
    }
  }
  
}

Exceptions are a great way of organizing your code runtime errors.

If you're writing a Library or any reusable code, you want to throw different exceptions when different things go wrong, so that the users of your library can do different actions in each case.

Thrown exceptions bubble up in the call stack until they are caught.