Skip to content

Exception Handling

What is Exception Handling?

Exception Handling in Java is a powerful mechanism that is used to handle the runtime errors so that the normal flow of the application can be maintained. In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.

The main advantage of exception handling is to maintain the normal flow of the application. An exception normally disrupts the normal flow of the application, which is why we use exception handling. Here is a hierarchy of Java Exception classes to give you a general idea:

java.lang.Throwable
    |__java.lang.Exception
        |__java.lang.RuntimeException
        |__Other exceptions

Causes of Exceptions

Divide by Zero: When an arithmetic operation attempts to divide a number by zero, an ArithmeticException is thrown.

int result = 10 / 0; // This will throw an ArithmeticException

Array Out of Bounds: When an attempt is made to access an index in an array that does not exist (such as if the index is negative or greater than the array's length minus 1), an ArrayIndexOutOfBoundsException is thrown.

int[] array = new int[5];
int value = array[10]; // This will throw an ArrayIndexOutOfBoundsException

Null Reference: When an attempt is made to call a method or access a property of an object that hasn't been instantiated (meaning, the object is null), a NullPointerException is thrown.

String str = null;
int length = str.length(); // This will throw a NullPointerException

These are just a few examples. Java has a large number of exception classes to handle various different types of exceptional situations. Note that exceptions are different from syntax errors or logical errors in your code. Exceptions are problems that arise while your program is running, not issues detected by the compiler.

Basic Structure of Exception Handling

Exception handling in Java uses five keywords: try, catch, finally, throw, and throws. The try and catch blocks are used to handle exceptions. The try block contains a block of code where an exception can occur, while the catch block is used to handle the exception. Here is the basic structure of a try/catch block:

try {
    // code that may raise an exception
} catch (ExceptionType name) {
    // code to handle the exception
}

Let's consider an example where we deliberately cause an exception to occur:

try {
    int divideByZero = 5 / 0;
    System.out.println("Rest of try block");
} catch (ArithmeticException e) {
    System.out.println("Arithmetic Exception: " + e.getMessage());
}

In this case, the ArithmeticException is caught and handled. The program does not terminate prematurely, and can continue with the next statements.

Tasks

In a new Java file named Week6Task2.java, complete the following tasks:

  1. Create a method named divide that takes two integer parameters and returns their quotient.
  2. In the divide method, include a try/catch block that will catch an ArithmeticException (which happens when you divide by zero).
  3. In the catch block, print a message that tells the user they cannot divide by zero.
  4. In your main() method, call the divide method with parameters that will cause an exception, and with parameters that will not.

Remember, the main goal here is to prevent the program from crashing when an exception occurs.

Answers

Additional Resources

W3 Schools - Java Exceptions

Oracle Docs - Exceptions