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, andfinally, - name the common exceptions and what causes them,
- signal errors with
throwand declare them withthrows, - compare arrays with
ArrayListand 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
DoneWhen 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, 2Order 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
| Exception | Typical cause |
|---|---|
ArithmeticException | integer division by zero |
ArrayIndexOutOfBoundsException | an array index below 0 or at least length |
IndexOutOfBoundsException | the same for an ArrayList |
NullPointerException | calling a method or reading a field through null |
NumberFormatException | Integer.parseInt("abc") |
InputMismatchException | Scanner.nextInt() reads text that isn't an int |
ClassCastException | a wrong downcast (lesson 17) |
IllegalArgumentException | a method got an invalid argument; you often throw this yourself |
IOException | a file or network problem |
SQLException | a database problem (lesson 19) |
Quick check
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.0Compare 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 asNullPointerExceptionandIllegalArgumentException, usually mean a bug or bad input. The compiler doesn't force you to handle them. - Checked exceptions, such as
IOExceptionandSQLException, 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 withthrowsin 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.
| Array | ArrayList | |
|---|---|---|
| Size | fixed when created | grows and shrinks |
| Create | String[] names = new String[40]; | ArrayList<String> names = new ArrayList<>(); |
| Add | names[count++] = "Ana"; (track count yourself) | names.add("Ana"); |
| Read | names[0] | names.get(0) |
| Change | names[0] = "Ben"; | names.set(0, "Ben"); |
| Size | names.length (capacity) | names.size() (items actually in it) |
| Element types | primitives or objects | objects 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 3Unlike an array, an ArrayList prints its contents directly. The main methods:
| Method | Does |
|---|---|
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
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.50Removing 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: 2put(key, value)adds a pair, or replaces the value if the key exists. Keys are unique; values may repeat.get(key)returns the value, ornullif the key isn't there.getOrDefault(key, fallback)avoids thenull.containsKey(key)checks whether a key exists;remove(key)deletes a pair.- A
HashMapdoesn't keep any order. If you loop over it, items may come out in any order. UseLinkedHashMapto keep insertion order, orTreeMapto 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: 1TreeMap 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
Common mistakes
- An empty
catchblock,catch (Exception e) {}, which hides errors. At least print the message. - Catching
Exceptionfirst, before more specific types. - Forgetting
in.next()after anInputMismatchException, which causes an endless loop. - Using
throwswhen you meanthrow, or the reverse. ArrayList<int>. Use the wrapper type:ArrayList<Integer>.list.lengthorlist[0]. For an ArrayList it'slist.size()andlist.get(0).- Removing items inside a for-each loop over the same list.
- Assuming a
HashMapkeeps order, or forgetting thatgetreturnsnullfor a missing key.
Summary
- An exception interrupts normal flow.
tryholds risky code,catchhandles a specific exception type, andfinallyalways runs. - Catch specific exceptions first. Learn the common ones:
NullPointerException,NumberFormatException,ArrayIndexOutOfBoundsException,ArithmeticException. throwraises an exception;throwsin a method header declares checked exceptions likeIOExceptionandSQLException. 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;TreeMapkeeps keys sorted.
That completes advanced OOP. Next comes connecting Java to MySQL with JDBC, where these tools come together.