Loading...

Java Exceptions

Keep a small int array slots that holds 2 and 4. Print slots[0] so the screen shows 2. Then learn what happens if you ask for slots[5] instead: Java throws ArrayIndexOutOfBoundsException and the program stops. Compile Alarm.java and run java Alarm for the safe file first. Seeing a run-time stop from a broken rule — not a missing semicolon — is what this page teaches. Leave try and catch for the next page.

A safe read that finishes

An exception is Java’s way of saying a rule broke while the program was running. Until now most demos printed a clear line and ended quietly. This page keeps one quiet demo first, then one demo that stops with an exception name.
Open Alarm.java. Keep the public class name Alarm so the file name matches. Delete leftover ArrayList<Integer>, nums.add(9), Crate demos, and any for-each over oak and pine. Also delete any Scanner or nextLine. The program must not wait for typing. This page needs no import line.
Inside main, store two whole numbers:
int[] slots = {2, 4};
Then print the first slot:
System.out.println(slots[0]);
Slot numbers start at zero. Slot zero holds 2. Save before you compile.

Alarm safe slots zero

java
public class Alarm {
    public static void main(String[] args) {
        int[] slots = {2, 4};
        System.out.println(slots[0]);
    }
}

From the folder that holds Alarm.java, run javac Alarm.java. When parentheses, braces, and semicolons match, javac writes no line of its own. Then run java Alarm — not java Alarm.java. Leave the .java ending off the run command.
The program should print one line and stop: 2. It should not ask you to type. If the terminal waits for keyboard input, a nextLine call from an older exercise is still in a file. Delete that call and keep the array plus System.out.println(slots[0]);.
Walk the run once. Java starts at Alarm.main. The array holds two values. The print reads slot zero. The screen shows 2. Nothing else should print. If you see 9, a Crate wrappers demo is still running — switch to java Alarm. If you see 4, you printed slots[1]; the safe teaching file keeps slots[0].

A bad index that throws

Change only the print line so it asks for a slot that was never written: slots[5]. The array still has only two slots. At run time Java throws an exception instead of printing a number.

Alarm bad index throws

java
public class Alarm {
    public static void main(String[] args) {
        int[] slots = {2, 4};
        System.out.println(slots[5]);
    }
}

Compile with javac Alarm.java, then run java Alarm. This time the program does not print 2. The terminal shows an error report that names ArrayIndexOutOfBoundsException. The run stops. Lines you might have imagined after that print do not run, because the exception already stopped the program. Notice that javac may still succeed — the bad index is a run-time problem, not a missing semicolon.
That stop is the lesson. You are not fixing the index on this page with try. You are learning to recognize that a broken rule at run time becomes an exception and ends the normal path. Read the exception name in the report. Keep the bad-index file only to see that stop. Prefer the safe file when you want a quiet screen with 2. If you change the bad index back to slots[0], the quiet screen returns; that proves the stop came from the index, not from the class name Alarm.
Do not treat the stack report as a normal println result. It is Java telling you what went wrong. Spelling of the exception type matters when you talk about it: ArrayIndexOutOfBoundsException. Saying only “error” is too vague for this lesson — keep the full type name when you describe the stop.

Wrappers leftover is not this crash

A third file reminds you of the previous page’s Integer list. That demo prints 9 and finishes. It is not the exception story.

Alarm wrappers leftover contrast

java
import java.util.ArrayList;

public class Alarm {
    public static void main(String[] args) {
        ArrayList<Integer> nums = new ArrayList<Integer>();
        nums.add(9);
        System.out.println(nums.get(0));
    }
}

That contrast prints 9 and ends without throwing. Use it only to separate a finished wrappers path from the bad-index Alarm path. For this exceptions lesson, the teaching pair is the safe slots[0] print and the throwing slots[5] print. Do not invent try or catch around either array demo on this page at all.

Compared with arrays and with wrappers

On the arrays page you stayed inside written slots. This page deliberately steps outside so you see the exception. On the wrappers page a list of Integer printed 9 without crashing. That still works as history. For this page keep Alarm and the array index story.
Other exceptions exist — for example dividing by zero can throw ArithmeticException. This page keeps one clear name: ArrayIndexOutOfBoundsException from a bad index. You do not need a catalog of every exception type today. One solid example is enough before the next page teaches handling.
When old Crate.java files still sit nearby, leave them alone or delete them only if they confuse which class you run. Run java Alarm after you compile the file for the demo you mean. Switch files deliberately so the safe print and the throwing print are not mixed in one main while you study.

What this leaves for try and catch

This page shows that an exception can stop a program at run time. The next page introduces try and catch so you can handle some problems without ending the whole run. Stay with recognizing the stop and the exception name here. Do not invent a catch block as a requirement on this page yet.

Before try and catch

You can print slots[0] from {2, 4} and see 2. You can print slots[5] and see the run stop with ArrayIndexOutOfBoundsException. Compile Alarm.java and run java Alarm for each kept demo in turn. The exception named the broken rule clearly. The next page is try and catch, where a handled path can continue after some errors.
Keep the safe demo for a quiet screen. Keep the bad index to see the stop. Keep try off this page. Those three habits are the checkpoint before you move on. When you can name ArrayIndexOutOfBoundsException after the bad index run of java Alarm, exceptions did their job for this lesson and you are ready for the next topic about handling.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
6
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top