Muhammad Fari Madyan
Hire me
Java basics · part 18 of 21

Learn Java from Scratch Part 18: Exceptions — Stack Traces, try, catch, finally & throw

The eighteenth part of a Java series: an exception as a red ball on the pile of trays, how to read a stack trace, try, catch and finally, throwing your own ball with throw, checked exceptions and throws, age input that survives typing mistakes, and three traps.

Muhammad Fari Madyan

· 7 min read

Baca dalam Bahasa Indonesia →

Introduction: A Promise from Part 6

The user types an age: tujuh belas ("seventeen"), in words. The program stops at once, and the screen fills with red text.

In Part 6, I promised to explain how to handle this. In this part I keep that promise: exceptions.

After this part, you will be able to:

  1. Read a stack trace, the red text you see when a program falls over.
  2. Catch problems with try, catch and finally.
  3. Throw your own problems with throw, and deal with checked exceptions.

Answer to the Part 17 Challenge

The question: an empty Robot meets the Sapa contract, and we call halo(). What is the output?

The answer is B: Halo.

A default method already has a body inside the interface. A Robot that meets the Sapa contract gets it for free, even though its class is empty.

If you answered B, well done!


1. The Problem: The World Is Not Tidy

Programs do not live in a tidy world:

  • users make typing mistakes,
  • files are not found,
  • the internet goes down,
  • numbers are divided by zero.

If every problem makes the program fall over, nobody can trust our app. We need a way to catch a problem and respond to it politely.


2. An Exception Is a Red Ball on the Pile of Trays

Remember the pile of trays from Part 13. main calls satu() ("one"), satu() calls dua() ("two"), and the trays pile up.

When something goes wrong in dua(), Java throws a red ball. That ball is called an exception.

  1. The red ball flies upward, past one tray after another.
  2. If a tray has a net, the ball is caught and the program goes on.
  3. If there is no net at all, the ball flies out of the pile, and the program stops with red text.

An exception is like a red ball flying up the pile of trays until a catch net stops it

Click the diagram to open it in full size.


3. Reading the Red Text: The Stack Trace

The file Main.java. nilai means "scores":

JAVA
void dua() {
    int[] nilai = {80, 75, 92};
    IO.println(nilai[5]);
}

void satu() {
    dua();
}

void main() {
    satu();
    IO.println("Selesai");
}
TEXT
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
	at Main.dua(Main.java:3)
	at Main.satu(Main.java:7)
	at Main.main(Main.java:11)

This red text is called a stack trace. It looks scary, but it is very helpful.

LineMeaning
The first lineThe kind of ball, ArrayIndexOutOfBoundsException, with its message
at Main.dua(Main.java:3)The ball was thrown in the method dua, line 3
at Main.satu(Main.java:7)The ball flew past satu, line 7
at Main.main(Main.java:11)Then past main, line 11, and out

Read from the top. The first line that names your own code is usually where the problem happened.

Notice also that Selesai ("done") is never printed. Once the ball leaves the pile, the program stops.


4. Setting Up a Net: try, catch, finally

JAVA
void main() {
    try {
        int umur = Integer.parseInt("tujuh belas");
        IO.println("Umur: " + umur);
    } catch (NumberFormatException e) {
        IO.println("Umur harus angka");
    } finally {
        IO.println("Pengecekan selesai");
    }
    IO.println("Program lanjut");
}
TEXT
Umur harus angka
Pengecekan selesai
Program lanjut

The lines mean "The age must be a number", "The check is done" and "The program goes on".

PieceIts job
try { ... }The area with code that might cause a problem
catch (NumberFormatException e)The net, only for that kind of ball
finally { ... }The part that always runs, with or without a ball

Follow the arrow:

  1. parseInt throws a NumberFormatException ball.
  2. The rest of the try block is skipped. Umur: ... is never printed.
  3. The catch net catches the ball, and a polite message is printed.
  4. finally runs.
  5. The program goes on to the next line.

finally is good for cleaning up, for example closing a file, because it runs no matter what happens.


5. Throwing Your Own Ball: throw

We can also throw a ball ourselves, with throw. Tarik means "withdraw":

JAVA
int saldo = 50_000;

void tarik(int jumlah) {
    if (jumlah > saldo) {
        throw new IllegalArgumentException("Saldo tidak cukup");
    }
    saldo -= jumlah;
}

void main() {
    try {
        tarik(20_000);
        IO.println("Sisa saldo: " + saldo);
        tarik(100_000);
        IO.println("Baris ini tidak dijalankan");
    } catch (IllegalArgumentException e) {
        IO.println("Gagal: " + e.getMessage());
    }
}
TEXT
Sisa saldo: 30000
Gagal: Saldo tidak cukup

The output means "Remaining balance: 30000" and "Failed: Balance is not enough".

throw new IllegalArgumentException(...) makes a new ball with a message, then throws it. The caller catches the ball and reads its message with e.getMessage().


6. Balls You Must Handle: Checked Exceptions

Some balls must be handled from the start. They are called checked exceptions.

One example is Thread.sleep(1000), which tells the program to sleep for 1,000 milliseconds, which is 1 second. javac does not let your program run until this ball is handled in one of two ways:

  • catch it with try and catch, or
  • announce it with the word throws, which means: "this method can throw this ball, and my caller deals with it".
JAVA
void main() throws InterruptedException {
    IO.println("Tunggu sebentar...");
    Thread.sleep(1000);
    IO.println("Selesai");
}
TEXT
Tunggu sebentar...
Selesai

Tunggu sebentar means "wait a moment".

Other balls, such as NumberFormatException and ArithmeticException, do not have to be handled. But if nobody catches them, the program still falls over.


7. A Real Example: Age Input That Survives Typing Mistakes

Now we combine input from Part 6, while from Part 8, and exceptions:

JAVA
void main() {
    int umur = -1;

    while (umur < 0) {
        try {
            umur = Integer.parseInt(IO.readln("Umur: "));
        } catch (NumberFormatException e) {
            IO.println("Masukkan angka, ya.");
        }
    }

    IO.println("Umurmu " + umur + " tahun");
}
TEXT
Umur: tujuh belas
Masukkan angka, ya.
Umur: 17
Umurmu 17 tahun

Masukkan angka, ya means "Please type a number". The user types tujuh belas. The program does not fall over. It just asks again. Then the user types 17, and the loop ends.

This is the difference between a friendly program and a fragile one.


8. Three Exception Traps

Trap one: an empty net.

JAVA
try {
    umur = Integer.parseInt(teks);
} catch (NumberFormatException e) {
}

A catch with nothing inside swallows the problem quietly. Your program does not fall over, but nobody knows something went wrong either. At the very least, print the message.

Trap two: nets in the wrong order.

JAVA
void main() {
    try {
        int umur = Integer.parseInt("tujuh belas");
    } catch (Exception e) {
        IO.println("Ada masalah");
    } catch (NumberFormatException e) {
        IO.println("Umur harus angka");
    }
}
TEXT
Main.java:6: error: exception NumberFormatException has already been caught
    } catch (NumberFormatException e) {
      ^
1 error
error: compilation failed

Exception is a general net that catches almost every ball. If it comes first, the specific net below it never gets a chance. Put the more specific net first.

Trap three: ignoring a checked exception.

JAVA
void main() {
    IO.println("Tunggu sebentar...");
    Thread.sleep(1000);
    IO.println("Selesai");
}
TEXT
Main.java:3: error: unreported exception InterruptedException; must be caught or declared to be thrown
    Thread.sleep(1000);
                ^
1 error
error: compilation failed

The message already gives you two choices: catch it, or declare it with throws, as in section 6.


Summary

  1. An exception is a red ball that flies up the pile of trays. A stack trace is its trail.
  2. try marks the area, catch catches a certain kind of ball, and finally always runs.
  3. throw throws your own ball. A checked exception must be caught or declared with throws.

Challenge

Look at this code:

JAVA
void main() {
    try {
        IO.println(1);
        IO.println(5 / 0);
        IO.println(2);
    } catch (ArithmeticException e) {
        IO.println(3);
    } finally {
        IO.println(4);
    }
}

What is the output, from top to bottom?

  • A. 1, 3, 4
  • B. 1, 2, 3, 4
  • C. 1, 3

Try to answer before you run it. I explain the answer at the start of Part 19.


Conclusion & What's Next

Your program can now fail gracefully, or not fail at all. If you remember only one thing, remember that the red text is not your enemy. A stack trace is a map that shows where the ball was thrown.

In Part 19, our arrays move up a level: a shelf that grows by itself, a filing cabinet with labels, and a bag that refuses duplicates.

See you in Part 19. Get your coffee ready. Hot chocolate is fine too.

ShareLinkedInXWhatsApp

Written by Muhammad Fari Madyan

Senior Backend Engineer and co-founder of LampungDev. I write up what I build so others can learn from it.

Work with me
← part 17Abstract Classes and Interfacespart 19 →Collections

Muhammad Fari Madyan

Senior Backend Engineer building real-time, high-concurrency systems that hold up in production. Co-founder of LampungDev. Based in Bandar Lampung, Indonesia (UTC+7), working remote.

Work

Case studiesCahTixExam platform, 4 stacksOpen source

© 2026 Muhammad Fari Madyan

Designed and built by Muhammad Fari Madyan