Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 06 / Topic 1 of 8

What happens without a catch

An exception is an object Java creates when something goes wrong while a program is running: bad input, a missing array slot, dividing by zero. If nothing in your code handles it, the JVM has no choice: it prints a stack trace to the screen and stops the program right there, at the line that failed. No code after that line runs, no matter what it was supposed to do.

Think of a bank teller who hits a problem mid-transaction and has no instructions for it: they stop serving you, write up an incident report, and the queue behind you doesn't move either.

Example 1: text that isn't a number. Asha's ATM reads a PIN as text and tries to convert it to a number with Integer.parseInt. The teller mistypes it as "12ab":

String pin = "12ab";
System.out.println("Converting PIN text to a number: " + pin);
int pinNumber = Integer.parseInt(pin);   // throws here, uncaught
System.out.println("PIN as a number: " + pinNumber);   // never printed

Real output (examples/NumberFormatCrash.java):

$ javac NumberFormatCrash.java
$ java NumberFormatCrash
Converting PIN text to a number: 12ab
Exception in thread "main" java.lang.NumberFormatException: For input string: "12ab"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
	at java.base/java.lang.Integer.parseInt(Integer.java:662)
	at java.base/java.lang.Integer.parseInt(Integer.java:778)
	at NumberFormatCrash.main(NumberFormatCrash.java:15)
$ echo "EXIT:$?"
EXIT:1

The last println never ran. The program's exit code is 1 (not 0), which is how a script or a shell would notice the program failed.

Example 2: a slot that doesn't exist. Ravi's ATM keeps the last 3 amounts in an array of length 3. Asking for a 4th (index 3, since arrays start at 0) doesn't exist:

int[] lastThreeAmounts = {500, 1200, 2000};
System.out.println("4th amount: " + lastThreeAmounts[3]);   // throws here, uncaught

Real output (examples/ArrayIndexCrash.java):

$ javac ArrayIndexCrash.java
$ java ArrayIndexCrash
Amounts array length: 3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
	at ArrayIndexCrash.main(ArrayIndexCrash.java:14)
$ echo "EXIT:$?"
EXIT:1

Different exception type (ArrayIndexOutOfBoundsException instead of NumberFormatException), same pattern: the JVM prints the trace and stops. The rest of this lesson is about taking control of that moment instead of letting the program die.

Full programs: examples/NumberFormatCrash.java, examples/ArrayIndexCrash.java.

Done here? The practice set for Part 6 — including the solutions — is on the part page.

Search the guide