Skip to content
Qyubie Learn
Java tutorialLesson 18 of 18 · tap to see all lessons

Java tutorial · Intermediate

Java Exception Handling and Collections: try-catch, throw, ArrayList, and HashMap

Handle errors in Java with try, catch, finally, throw, and throws, learn the common exceptions, and store objects in a growable ArrayList and a HashMap.

  • Qyubie Learn Editorial Team
  • Published
  • 17 min read

Includes 3 quick checks you can do right here.

Two problems show up as soon as a program meets real users and real data. Users type "abc" where a number belongs, files go missing, and databases go offline, and without a plan the program just crashes. And the number of records is never known in advance, so a fixed-size array either runs out of room or wastes it. This lesson solves both: exception handling for errors, and collections for groups of objects that grow and shrink. You'll need both when Java talks to MySQL in the next lesson.

By the end of this lesson you will be able to:

  • catch and handle exceptions with try, catch, and finally,
  • name the common exceptions and what causes them,
  • signal errors with throw and declare them with throws,
  • compare arrays with ArrayList and use ArrayList's main operations, and
  • store and look up values by key with HashMap.

What an exception is

An exception is an event that interrupts the normal flow of a program, usually an error. When one is thrown and nothing catches it, the program stops and prints a stack trace:

int[] scores = {90, 85};
System.out.println(scores[5]);
// Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
//     Index 5 out of bounds for length 2
//     at Main.main(Main.java:4)

The stack trace tells you the exception's type, a message, and the line where it happened. Read it from the top: it's the fastest way to find a bug.

try and catch

Put code that might fail in a try block, and the code that handles the failure in a catch block:

public class Main {
    public static void main(String[] args) {
        String[] inputs = {"18", "abc", "21"};
        for (String text : inputs) {
            try {
                int age = Integer.parseInt(text);     // may throw
                System.out.println("Age: " + age);
            } catch (NumberFormatException e) {
                System.out.println("'" + text + "' is not a number");
            }
        }
        System.out.println("Done");
    }
}

Output:

Age: 18
'abc' is not a number
Age: 21
Done

When parseInt("abc") throws, Java skips the rest of the try block and jumps to the matching catch. After the catch, the program carries on normally, so the loop continues and "Done" is printed.

Inside the catch, e is the exception object. e.getMessage() gives its message, which is useful for logs.

Reading input safely

A classic use: keep asking until the user types a valid number. Scanner.nextInt() throws an InputMismatchException when the input isn't a whole number:

import java.util.InputMismatchException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int age = -1;
        while (age < 0) {
            System.out.print("Age: ");
            try {
                age = in.nextInt();
                if (age < 0) {
                    System.out.println("Age can't be negative.");
                }
            } catch (InputMismatchException e) {
                System.out.println("Please type a whole number.");
                in.next();          // throw away the bad input, or it's read again forever
            }
        }
        System.out.println("Saved: " + age);
    }
}

Output:

Age: Please type a whole number.
Age: Age can't be negative.
Age: Saved: 19

(The input typed was abc, -5, and 19; typed input doesn't appear in the output.) The in.next() line matters: a failed nextInt() leaves the bad text waiting, and without clearing it the loop would fail on the same text forever.

Several catch blocks and finally

One try can have several catch blocks, checked top to bottom. A finally block runs every time, whether an exception happened or not, so it's where clean-up goes, such as closing a file or a database connection:

public class Main {
    static void divide(String a, String b) {
        try {
            int x = Integer.parseInt(a);
            int y = Integer.parseInt(b);
            System.out.println(x + " / " + y + " = " + (x / y));
        } catch (NumberFormatException e) {
            System.out.println("Not a number");
        } catch (ArithmeticException e) {
            System.out.println("Can't divide by zero");
        } finally {
            System.out.println("-- finished " + a + ", " + b);
        }
    }

    public static void main(String[] args) {
        divide("10", "2");
        divide("10", "0");
        divide("ten", "2");
    }
}

Output:

10 / 2 = 5
-- finished 10, 2
Can't divide by zero
-- finished 10, 0
Not a number
-- finished ten, 2

Order the catch blocks from most specific to most general. catch (Exception e) catches nearly everything, so if it came first, the specific blocks below it could never run, and the compiler reports an error.

Common exceptions

ExceptionTypical cause
ArithmeticExceptioninteger division by zero
ArrayIndexOutOfBoundsExceptionan array index below 0 or at least length
IndexOutOfBoundsExceptionthe same for an ArrayList
NullPointerExceptioncalling a method or reading a field through null
NumberFormatExceptionInteger.parseInt("abc")
InputMismatchExceptionScanner.nextInt() reads text that isn't an int
ClassCastExceptiona wrong downcast (lesson 17)
IllegalArgumentExceptiona method got an invalid argument; you often throw this yourself
IOExceptiona file or network problem
SQLExceptiona database problem (lesson 19)

Quick check

What does this print?
public class Main {
    public static void main(String[] args) {
        try {
            String s = null;
            System.out.print("A");
            System.out.print(s.length());
            System.out.print("B");
        } catch (NullPointerException e) {
            System.out.print("C");
        } finally {
            System.out.print("D");
        }
        System.out.print("E");
    }
}

Throwing your own: throw and throws

Your own methods can report errors too. throw creates and throws an exception, for example when an argument breaks the rules:

class Account {
    private double balance;

    void withdraw(double amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("Amount must be positive");
        }
        if (amount > balance) {
            throw new IllegalStateException("Insufficient balance");
        }
        balance -= amount;
    }

    void deposit(double amount) {
        balance += amount;
    }

    double getBalance() {
        return balance;
    }
}

public class Main {
    public static void main(String[] args) {
        Account acc = new Account();
        acc.deposit(500);
        double[] requests = {200, -10, 1000};
        for (double r : requests) {
            try {
                acc.withdraw(r);
                System.out.println("Withdrew " + r);
            } catch (IllegalArgumentException | IllegalStateException e) {
                System.out.println("Refused: " + e.getMessage());
            }
        }
        System.out.println("Balance: " + acc.getBalance());
    }
}

Output:

Withdrew 200.0
Refused: Amount must be positive
Refused: Insufficient balance
Balance: 300.0

Compare this with lesson 12, where withdraw printed a message itself. Throwing is better design: the Account class reports the problem, and the caller decides what to do with it (show a dialog, log it, try again). catch (A | B e) handles two exception types with one block.

Checked and unchecked exceptions, and throws

Java has two kinds of exceptions:

  • Unchecked exceptions (subclasses of RuntimeException), such as NullPointerException and IllegalArgumentException, usually mean a bug or bad input. The compiler doesn't force you to handle them.
  • Checked exceptions, such as IOException and SQLException, are problems outside your program's control: a missing file, a database that's down. The compiler requires you either to catch them or to declare them with throws in the method header, passing the job to the caller:
import java.io.FileReader;
import java.io.IOException;

public class Main {
    static int firstChar(String path) throws IOException {   // "I might throw this"
        try (FileReader reader = new FileReader(path)) {
            return reader.read();
        }
    }

    public static void main(String[] args) {
        try {
            System.out.println(firstChar("missing.txt"));
        } catch (IOException e) {
            System.out.println("Could not read the file: " + e.getMessage());
        }
    }
}

try (FileReader reader = ...) is a try-with-resources: Java closes the reader automatically at the end, even if an exception happens, so you don't need a finally for it. You'll use the same pattern for database connections in lesson 19, where nearly every JDBC method throws SQLException.

throw vs throws: throw is a statement that throws one exception now; throws is part of a method's header that warns callers it might.

From arrays to ArrayList

Arrays have a fixed length. To enroll a 41st student in a Student[40], you'd have to create a bigger array and copy everything over. An ArrayList does that for you: it's a list that grows and shrinks as you add and remove items.

ArrayArrayList
Sizefixed when createdgrows and shrinks
CreateString[] names = new String[40];ArrayList<String> names = new ArrayList<>();
Addnames[count++] = "Ana"; (track count yourself)names.add("Ana");
Readnames[0]names.get(0)
Changenames[0] = "Ben";names.set(0, "Ben");
Sizenames.length (capacity)names.size() (items actually in it)
Element typesprimitives or objectsobjects only (Integer, not int)

The type in angle brackets, <String>, says what the list holds; this is called a generic type. For numbers, use the wrapper classes: ArrayList<Integer>, ArrayList<Double>. Java converts between int and Integer automatically.

ArrayList operations

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> subjects = new ArrayList<>();
        subjects.add("CS 122");
        subjects.add("GE 5");
        subjects.add("PE 2");
        subjects.add(1, "MATH 3");          // insert at index 1
        System.out.println(subjects);
        System.out.println("Size: " + subjects.size());
        System.out.println("First: " + subjects.get(0));

        subjects.set(3, "PE 3");            // replace
        subjects.remove("GE 5");            // remove by value
        System.out.println(subjects);

        System.out.println(subjects.contains("CS 122"));
        System.out.println(subjects.indexOf("PE 3"));

        for (String s : subjects) {
            System.out.println("- " + s);
        }
    }
}

Output:

[CS 122, MATH 3, GE 5, PE 2]
Size: 4
First: CS 122
[CS 122, MATH 3, PE 3]
true
2
- CS 122
- MATH 3
- PE 3

Unlike an array, an ArrayList prints its contents directly. The main methods:

MethodDoes
add(x) / add(i, x)add at the end / at index i
get(i)the item at index i
set(i, x)replace the item at index i
remove(i) / remove(x)remove by index / the first item equal to x
size()number of items
contains(x), indexOf(x)search (uses equals); indexOf gives -1 if absent
isEmpty(), clear()check for no items / remove all

Be careful with ArrayList<Integer>: list.remove(1) removes the item at index 1, not the number 1. Use list.remove(Integer.valueOf(1)) to remove by value.

Quick check

What does this print?
import java.util.ArrayList;
public class Main {
    public static void main(String[] args) {
        ArrayList<String> q = new ArrayList<>();
        q.add("Ana");
        q.add("Ben");
        q.add(0, "Cara");
        q.remove("Ana");
        q.add("Dan");
        System.out.println(q.get(1) + " " + q.size());
    }
}

An ArrayList of objects

An ArrayList can hold any objects, which makes it the natural replacement for the Student[40] array in lesson 13's Section. It's also exactly what a database query will give you in the next lesson: a list of objects, one per row.

import java.util.ArrayList;

class Student {
    private String name;
    private double grade;

    Student(String name, double grade) {
        this.name = name;
        this.grade = grade;
    }

    String getName() { return name; }
    double getGrade() { return grade; }
}

public class Main {
    public static void main(String[] args) {
        ArrayList<Student> roster = new ArrayList<>();
        roster.add(new Student("Ana", 92));
        roster.add(new Student("Ben", 74));
        roster.add(new Student("Cara", 85));

        // remove failing students while looping: use removeIf, not a for-each loop
        roster.removeIf(s -> s.getGrade() < 75);

        double sum = 0;
        for (Student s : roster) {
            System.out.println(s.getName() + " " + s.getGrade());
            sum += s.getGrade();
        }
        System.out.printf("Average of %d: %.2f%n", roster.size(), sum / roster.size());
    }
}

Output:

Ana 92.0
Cara 85.0
Average of 2: 88.50

Removing items inside a for-each loop over the same list throws a ConcurrentModificationException. removeIf does it safely; s -> s.getGrade() < 75 is a short lambda meaning "for each s, remove it if this is true".

HashMap: looking things up by key

A list is good when you go through items in order. When you need to find an item by something like its ID, use a HashMap. It stores key → value pairs, and finding a value by its key is very fast, even with thousands of entries.

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        HashMap<String, String> students = new HashMap<>();
        students.put("2024-0001", "Ana Reyes");
        students.put("2024-0002", "Ben Cruz");
        students.put("2025-0001", "Cara Lim");

        System.out.println(students.get("2024-0002"));
        System.out.println(students.get("9999-0000"));         // no such key
        System.out.println(students.containsKey("2025-0001"));

        students.put("2024-0002", "Benjamin Cruz");             // same key: replaces
        students.remove("2025-0001");
        System.out.println(students.get("2024-0002"));
        System.out.println("Size: " + students.size());
    }
}

Output:

Ben Cruz
null
true
Benjamin Cruz
Size: 2
  • put(key, value) adds a pair, or replaces the value if the key exists. Keys are unique; values may repeat.
  • get(key) returns the value, or null if the key isn't there. getOrDefault(key, fallback) avoids the null.
  • containsKey(key) checks whether a key exists; remove(key) deletes a pair.
  • A HashMap doesn't keep any order. If you loop over it, items may come out in any order. Use LinkedHashMap to keep insertion order, or TreeMap to keep keys sorted.

A common pattern is counting with a map:

import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        String[] courses = {"BSCS", "BSIT", "BSCS", "BSIT", "BSCS", "BSMATH"};
        TreeMap<String, Integer> count = new TreeMap<>();     // sorted by key
        for (String c : courses) {
            count.put(c, count.getOrDefault(c, 0) + 1);
        }
        for (String course : count.keySet()) {
            System.out.println(course + ": " + count.get(course));
        }
    }
}

Output:

BSCS: 3
BSIT: 2
BSMATH: 1

TreeMap works exactly like HashMap here, but it keeps the keys sorted, so the output order is predictable. Both are kinds of Map, just as ArrayList is a kind of List. You'll often see variables declared by the interface, List<Student> roster = new ArrayList<>();, which is the polymorphism from lesson 17 at work.

Quick check

Which collection fits best: look up a subject's title quickly when given its code, like "CS 122"?

Common mistakes

  • An empty catch block, catch (Exception e) {}, which hides errors. At least print the message.
  • Catching Exception first, before more specific types.
  • Forgetting in.next() after an InputMismatchException, which causes an endless loop.
  • Using throws when you mean throw, or the reverse.
  • ArrayList<int>. Use the wrapper type: ArrayList<Integer>.
  • list.length or list[0]. For an ArrayList it's list.size() and list.get(0).
  • Removing items inside a for-each loop over the same list.
  • Assuming a HashMap keeps order, or forgetting that get returns null for a missing key.

Summary

  • An exception interrupts normal flow. try holds risky code, catch handles a specific exception type, and finally always runs.
  • Catch specific exceptions first. Learn the common ones: NullPointerException, NumberFormatException, ArrayIndexOutOfBoundsException, ArithmeticException.
  • throw raises an exception; throws in a method header declares checked exceptions like IOException and SQLException. Try-with-resources closes resources automatically.
  • ArrayList<T> is a growable list: add, get, set, remove, size, contains.
  • HashMap<K, V> stores key → value pairs for fast lookup: put, get, getOrDefault, containsKey, remove. It keeps no order; TreeMap keeps keys sorted.

That completes advanced OOP. Next comes connecting Java to MySQL with JDBC, where these tools come together.

References and further reading