HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

2) Exception Handling Lesson

Java: Try Catch

7 min to complete · By Ryan Desmond

A try-catch block is the foundation of all Exception handling.

How to Use the Try-Catch Block?

The two keywords are used together. Thus, you cannot have a catch without a try, nor can you have a try without a catch.

What is Inside a Try Block?

try block is used to contain a section of code that could possibly cause an Exception. In essence, you are trying to accomplish the following actions, but it might fail. In which case, you'll catch the Exception that gets sent.

What is Inside a Catch Block?

The catch block is used to handle the Exception that is thrown inside of the try block in a graceful way and must specify the type of Exception that could be thrown inside the try block.

For example, you might want to send the user a detailed message of what might have happened, such as "You do not have the rights to access this page".

Syntax

The general form of a try-catch block is as follows:

try{
    // block of code to monitor for errors
} catch (Exception one){
    // handle for Exception one
}

Can you Do Multiple Catch Blocks?

In Java, it is possible to catch multiple exceptions using one try block. This requires a catch statement for each Exception that could be thrown. Therefore, multiple catch statements can be used for one try block if there is a chance two different exceptions could be thrown.

For example, if you were trying to divide two numbers in two indexes of an array, there is a chance an ArithmeticException or an ArrayIndexOutOfBounds could be thrown. Having a catch statement for each allows the program to handle one or the other.

int[] nums = {3,0,7,9};

try{
    // block of code to monitor for errors
    // this will throw an ArithmeticException
    // you cannot divide by zero
    int x = nums[0] / nums[1]; 

     // this would throw an ArrayIndexOutOfBoundsException
    // int y = nums[10];
} catch (ArithmeticException  one){
    // handle for Exception one
} catch(ArrayIndexOutOfBoundsException two){
    // handle for Exception two
}

Subclass Exceptions

When handling multiple exceptions, it is important to remember that the subclass must be caught before the superclass. Each Exception subclass already provides information with its name, and it also comes with additional information to help both you and the user understand what is happening.

For example, an ArrayIndexOutOfBoundException (which is a subclass of Exception) must be caught before Exception in the catch hierarchy. This is because Exception will catch all of its subclass's exceptions but will not give the detail that the ArrayIndexOutOfBoundException could provide.

Can You Nest Try-Catch Blocks?

The try-catch block can be nested within itself. In this case, if an Exception is not caught within the nested try block, the outer try block is able to catch it. Outer blocks can be used as another default option.

For example, an inner try block will try to handle an error gracefully, but if it cannot, the outer block can catch it and terminate the program.

try{
    // block of code to monitor for errors
} catch (Exception one){
    // handle for Exception one
    try {
        // block of code - nested try
    } catch {
        // handle any exception that 
        // occurs inside the nested try
    }
}

Experiment with Exception Handling

  1. Run the following code as is.

    • Do you see the exception thrown?
    • Does "Program Complete" print?
  2. Uncomment the try/catch block (the 4 lines that start with "//"), then run the application again.

    • See the difference?
    • Did "Program complete" print?
  3. Try to generate a new exception and catch it properly.

class Main {
   public static void main(String[] args) {
    
      int[] nums = {67, 43};

      // try {
         System.out.println(nums[5]);
      // } catch (ArrayIndexOutOfBoundsException exc){
      //   System.out.println("Exception caught");
      //   System.out.println("You attempted to access index " + 5);
      //   System.out.println("The array has a length of " + nums.length);
      // }

      System.out.println("Program complete");
   }
}

Summary: Java: Try Catch

  • The try-catch block is the foundation of Exception handling in Java
  • You can't have a try without a catch and vice versa
  • The try section will attempt to run a section of code
  • The catch section will activate if an applicable Exception is generated
  • You can add multiple catch blocks to each try block
  • The try-catch block can be nested within itself

Syntax

try{
    // block of code to monitor for errors
} catch (Exception one){
    // handle for Exception one
}