Aral Code

Going Further Lesson 20 of 21

Java Exceptions — try, catch, finally and throw

Handle runtime errors with try, catch and finally, know common exceptions like NumberFormatException and ArithmeticException, throw your own, and read and write files safely.

Some errors only happen while the program runs: a user types "abc" instead of a number, a file is missing, someone divides by zero. Java calls these exceptions. If you don't handle them, the program crashes. If you do, it can recover gracefully.

An unhandled exception

public class Main {
    public static void main(String[] args) {
        int qty = Integer.parseInt("sampu");
        System.out.println(qty);
    }
}

Error

Exception in thread "main" java.lang.NumberFormatException: For input string: "sampu"
	at java.base/java.lang.Integer.parseInt(Integer.java:661)
	at Main.main(Main.java:3)

The stack trace tells you the exception type, the message, and the line in your code (Main.java:3).

try and catch

public class Main {
    public static void main(String[] args) {
        String input = "sampu";
        try {
            int qty = Integer.parseInt(input);
            System.out.println("Quantity: " + qty);
        } catch (NumberFormatException e) {
            System.out.println("\"" + input + "\" is not a number. Please use digits.");
        }
        System.out.println("The program continues.");
    }
}

Output

"sampu" is not a number. Please use digits.
The program continues.

If anything inside try throws the named exception, Java jumps straight to the matching catch, and then continues after it.

Common exceptions

ExceptionTypical cause
NumberFormatExceptionInteger.parseInt("abc")
InputMismatchExceptionScanner's nextInt() gets letters
ArithmeticExceptionInteger division by zero
ArrayIndexOutOfBoundsExceptionarr[10] in a smaller array
NullPointerExceptionCalling a method on null
FileNotFoundExceptionOpening a file that doesn't exist

Several catch blocks

public class Main {
    public static void main(String[] args) {
        String[] inputs = {"120", "abc", "0"};
        for (String in : inputs) {
            try {
                int people = Integer.parseInt(in);
                int share = 600 / people;
                System.out.println(in + " people: ₱" + share + " each");
            } catch (NumberFormatException e) {
                System.out.println(in + ": not a number");
            } catch (ArithmeticException e) {
                System.out.println(in + ": can't split among zero people");
            }
        }
    }
}

Output

120 people: ₱5 each
abc: not a number
0: can't split among zero people

finally

A finally block runs whether an exception happened or not. It's used for cleanup, like closing files:

public class Main {
    public static void main(String[] args) {
        try {
            System.out.println("Connecting to printer...");
            int[] pages = new int[3];
            pages[5] = 1;
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: " + e.getMessage());
        } finally {
            System.out.println("Printer connection closed.");
        }
    }
}

Output

Connecting to printer...
Error: Index 5 out of bounds for length 3
Printer connection closed.

Safe Scanner input

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int grade = -1;
        while (grade < 0 || grade > 100) {
            System.out.print("Enter grade (0-100): ");
            try {
                grade = Integer.parseInt(sc.nextLine().trim());
                if (grade < 0 || grade > 100) System.out.println("Out of range.");
            } catch (NumberFormatException e) {
                System.out.println("Numbers only.");
            }
        }
        System.out.println("Saved: " + grade);
    }
}

Output

Enter grade (0-100): ninety
Numbers only.
Enter grade (0-100): 150
Out of range.
Enter grade (0-100): 93
Saved: 93

throw: raising your own exception

public class Main {
    static void setGrade(int grade) {
        if (grade < 0 || grade > 100) {
            throw new IllegalArgumentException("Invalid grade: " + grade);
        }
        System.out.println("Grade set to " + grade);
    }

    public static void main(String[] args) {
        try {
            setGrade(88);
            setGrade(120);
        } catch (IllegalArgumentException e) {
            System.out.println("Problem: " + e.getMessage());
        }
    }
}

Output

Grade set to 88
Problem: Invalid grade: 120

Checked exceptions and files

Some exceptions, like IOException for files, are checked: Java forces you to handle them (or declare them with throws). The modern way to read and write a text file:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        Path file = Path.of("students.txt");
        try {
            Files.write(file, List.of("Ana,91", "Ben,84", "Carla,95"));
            for (String line : Files.readAllLines(file)) {
                String[] parts = line.split(",");
                System.out.println(parts[0] + " got " + parts[1]);
            }
        } catch (IOException e) {
            System.out.println("File error: " + e.getMessage());
        }
    }
}

Output

Ana got 91
Ben got 84
Carla got 95

Quick Quiz

Check what you learned. Walang grade ito, practice lang. 🙂

1. Which exception does Integer.parseInt("12a") throw?
2. When does the finally block run?
3. What does throw do?
4. Why is an empty catch block bad?

By Sir Reyel · Last updated 2026-12-04