Throwing and Propagating Exceptions

Tutorial 3 of 5

Introduction

In this tutorial, we will learn how to throw and propagate exceptions in Java. An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

Goals:
- Understand what exceptions are
- Learn how to manually throw exceptions
- Understand how exception propagation works
- Learn how to control the propagation of exceptions

You will learn how to:
- Use the throw keyword
- Understand the throws keyword
- Propagate exceptions
- Handle exceptions

Prerequisites:
To get the most from this tutorial, you should have basic knowledge of Java programming, particularly functions and control flow.

Step-by-Step Guide

Throwing Exceptions

In Java, exceptions are thrown using the throw keyword. After the throw keyword, an instance of an exception class is written. This can be an instance of an existing exception class, like ArithmeticException, or a custom exception class that you create.

Example:

throw new ArithmeticException("Dividing by zero!");

Propagating Exceptions

In Java, checked exceptions need to be declared in the method signature if they can be thrown and are not caught within the method. This is done using the throws keyword.

Example:

public void myMethod() throws IOException {
    // code that may throw IOException
}

Code Examples

Example 1: Throwing an Exception

In this example, we will throw an ArithmeticException when a division by zero is attempted.

public class Main {
    public static void main(String[] args) {
        try {
            int result = divide(10, 0);
        } catch (ArithmeticException e) {
            System.out.println("Caught exception: " + e.getMessage());
        }
    }

    public static int divide(int a, int b) {
        if (b == 0) {
            throw new ArithmeticException("Cannot divide by zero!");
        }
        return a / b;
    }
}

Example 2: Propagating an Exception

In this example, we will propagate an IOException from a method to the main function.

import java.io.*;

public class Main {
    public static void main(String[] args) {
        try {
            readFromFile("nonexistent_file.txt");
        } catch (IOException e) {
            System.out.println("Caught exception: " + e.getMessage());
        }
    }

    public static void readFromFile(String fileName) throws IOException {
        File file = new File(fileName);
        FileReader fr = new FileReader(file);
    }
}

Summary

  • We've learned how to throw exceptions using the throw keyword.
  • We understood how exceptions propagate through the call stack.
  • We learned to control the propagation of exceptions using the throws keyword.

To learn more about exceptions, you can check out the Java Documentation.

Practice Exercises

  1. Write a function that throws a NullPointerException when a null argument is passed.
  2. Write a function that propagates an IOException.
  3. Write a function that catches an ArithmeticException and rethrows it as a IllegalArgumentException.

Remember, the best way to learn is by doing. Practice these exercises and experiment with different cases to fully understand exception handling in Java.