Lesson 11

Error Handling

Author: Brandon Fajardo (11/10/17). Updated (8/7/20)

Introduction

So far, we have assumed that the user is someone who either 1.) understands how to not break the code or 2.) does not intend to nefariously break the code.

Yet, when we wish to give our code to other people, this is often not the case. For this reason, we often want to prevent certain code-breaking errors from happening. One way we do this is by using try catch.

Topic 1 - Try Catch

Try Catch: a set of statements which attempt to prevent exceptions (errors) from occurring.

Try-catch is a two-part statement that initially tries a block of code and catch, in the case of some error, prevents the code from erroring.

The notation is as follows:

try {
 action(s)
} catch (condition) {
 action(s)
} finally {
 action(s)
}

Statement

Usage

Try

Within this block of code is everything that we wish to check for errors.

You may only use one.

Catch

This statement deals with any errors which may occur in the try block.

You may use any number of catch statements to catch various errors and do different things as a result.

If successful, an error will be handled and the code will not stop running.

Finally

This statement will run its block of code after try and catch regardless of the results of the previous.

Even if an error has occurred that was not handled by a catch, finally will still run.

Topic 2 - Throw

Subtopic 1 - Definition

throw x;

This code is a little different from what we usually do in Java. What this does is it creates an error with a customizable message.

Normally, when code is invalid, Java sends out its own error message and stops the code from running. Now, you can send an error which has a custom message. This error is defined in the throw statement.

Subtopic 2 - Throw without Try-Catch

Throw does not need to be paired with try catch. It can be used otherwise/alone.

EX:

if (t/0 != 0){
     throw new IllegalArgumentException("No divide by zero pl0z");
}

(Example given by Anthony Nuon-Prak)

Topic 3 - Imports

To be able to catch certain errors, certain imports may be necessary.

Error name

Description

ArithmeticException

Math errors (division by 0, even roots of negative numbers)

IOException

Deals with files

Input/Output Exception

InputMismatchException

Deals with Scanner, inputting wrong data type

NullPointerException

Deals with variables (null variables)

IllegalStateException

Deals with “throw clause”

ArrayIndexOutOfBoundsException

Deals with arrays and elements being referenced (by their index) which do not exist

Example:

Scanner x = new Scanner(System.in);
try{
    int i = x.nextInt();
    System.out.println(1/i);
} catch(ArithmeticException e){
    System.out.println("NO DIVIDING BY ZERO");
} catch(InputMismatchException e){
    System.out.println("NO PUTTING TEXT");
} finally {
    System.out.println("This statement runs no matter what”);
}

This code attempts to divide 1 by an inputted variable. The first catch statement protects against dividing by zero. The second catch statement protects against using different data types.

Example

Scanner x = new Scanner(System.in);
try {
    double i = x.nextDouble();
} catch (InputMismatchException e) {
    throw null;
} finally {
    System.out.println("Runs no matter what");
    int y = 0;
    while (y<100) {
        y++;
        System.out.println(y);
    }

Here, even if the catch statement throws a null, the finally statement will still print the numbers from 0 to 100.

If a null is thrown in the finally statement though, everything after the throw will not work though as everything in the statement is still affected by it.

Note:

  • e is an arbitrary variable and stands for exception. Like other variables, it cannot be used twice without one overwriting the other.

Example - Finally

Scanner s = new Scanner(System.in);
System.out.println("Enter a number: ");
try {
    double equality = s.nextDouble();
} catch (InputMismatchException x) {
    throw new InputMismatchException("Enter a valid integer");
} finally {
    System.out.println("Listen to the directions");
}

(Example provided by Letsy Cahue-Flores)

Conclusion

Recap: In this lesson, we learned how to handle errors caused by unexpected actions. We learned about try, catch, and finally. We also learned how to throw errors with throw.

Next: In the next lesson, we will learn about our last topic, arrays.

Last updated

Was this helpful?