Loading...

Java try and catch

Wrap the bad slots[5] read in try and catch so the program does not end on ArrayIndexOutOfBoundsException. Print blocked inside the catch, then print after outside both blocks. Compile Guard.java and run java Guard. The screen should show blocked, then after. A second file keeps slots[0] inside try so the catch is skipped and the screen shows 2, then after. Leave throw for the next page.

Catch the bad index

The exceptions page showed that printing slots[5] on {2, 4} throws ArrayIndexOutOfBoundsException and stops the run. This page keeps the same array story and adds handling. Open a new teaching file named Guard.java. Keep the public class name Guard so the file name matches. Delete leftover Alarm mains that stop without a catch, leftover Crate Integer lists, and any Scanner or nextLine. The program must not wait for typing.
Inside main, keep the same small array:
int[] slots = {2, 4};
Put the bad print inside try:
System.out.println(slots[5]);
Then write a catch that names ArrayIndexOutOfBoundsException and prints blocked. After the whole try and catch, print after. The catch parameter name can be a short letter such as e; you do not need to print the exception object on this page.

Guard catch bad index

java
public class Guard {
    public static void main(String[] args) {
        int[] slots = {2, 4};
        try {
            System.out.println(slots[5]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("blocked");
        }
        System.out.println("after");
    }
}

From the folder that holds Guard.java, run javac Guard.java. When parentheses, braces, and semicolons match, javac writes no line of its own. Then run java Guard — not java Guard.java. Leave the .java ending off the run command.
The screen shows blocked, then after. The bad index still throws inside try. The catch handles that named exception and prints blocked. The line System.out.println("after"); sits outside, so it still runs. The program does not end on that stop the way the bare Alarm bad-index file did.
Imagine a second print still inside try after slots[5], for example a line that would print rice. That line does not run. Catching the exception does not go back and finish the rest of try. Only the catch body runs for that stop, then control continues after the catch. Keep that idea clear: handling skips the leftover lines inside try after the throw point.
If the terminal waits for keyboard input, a nextLine call from an older exercise is still in a file. Delete that call. If you see only a stack report and no blocked line, the catch is missing or the exception name does not match. If you see 2 alone with no after, you may still be running an old safe Alarm file — switch to java Guard with the catch teaching file.

When try finishes, catch stays quiet

A second program uses the same try and catch shape, but the print inside try asks for a written slot: slots[0]. Every line inside try finishes. The catch body does not run.

Guard safe index skips catch

java
public class Guard {
    public static void main(String[] args) {
        int[] slots = {2, 4};
        try {
            System.out.println(slots[0]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("blocked");
        }
        System.out.println("after");
    }
}

Compile with javac Guard.java, then run java Guard. The screen shows 2, then after. The word blocked is not printed, because there was no ArrayIndexOutOfBoundsException. The catch stayed quiet. The after line still runs, because it sits outside both blocks — the same place it had in the catch demo.
Walk the contrast once. First file: bad index, catch prints blocked, then after. Second file: safe index, catch skipped, screen shows 2, then after. Both keep Guard and the same catch type name. Only the index inside try changes. That single change is enough to show when catch runs and when it does not.
Do not invent a throw statement on this page. You are catching an exception a bad array read already causes. The next page is about throwing on purpose. Also do not wrap every quiet print in the course inside try today — this lesson uses try where a known bad index needs a handled path.

The catch name must match

The catch clause names one exception type. On this page that type is ArrayIndexOutOfBoundsException, matching the bad index. If you wrote catch (NullPointerException e) around slots[5] instead, that catch would not handle the stop. The program would still end with ArrayIndexOutOfBoundsException, and neither blocked nor after would print for that mismatched catch. Keep the matching type in the teaching files.
Other exception names exist in Java. This page stays with one clear pair: a bad array index and ArrayIndexOutOfBoundsException. You do not need a catalog of every catchable type before you practice this shape. Match the name you saw on the exceptions page.

Compared with the bare Alarm stop

On the exceptions page, java Alarm with slots[5] stopped and showed a stack report. On this page, java Guard with the same bad index prints blocked and continues to after. The array story did not change. Handling did. Keep Alarm files only as history if they still sit nearby; run java Guard for the catch demos so the screen matches this lesson.
Wrappers history still prints 9 from an Integer list when you keep that older file. That path is not the catch story. Delete or ignore leftover ArrayList<Integer> demos inside Guard.java so the teaching file stays on int[] slots plus try and catch.

What this leaves for throwing

This page catches an exception a line already hits. The next page introduces throw so you can signal a problem yourself. Stay with matching catch and seeing after continue here. Do not add a manual throw as a requirement on these Guard files yet.

Before throwing

You can catch ArrayIndexOutOfBoundsException from slots[5] and see blocked, then after. You can keep slots[0] inside try and see 2, then after, with catch skipped. Compile Guard.java and run java Guard for each kept demo in turn. The catch name matched the bad-index stop. The next page is throwing, where you cause a stop on purpose.
Keep the catch demo for a handled path. Keep the safe try for a quiet skip of catch. Keep manual throw off this page. Those three habits are the checkpoint before you move on. When blocked then after appear after the bad index run of java Guard, try and catch did their job for this lesson and you are ready for the next topic about throwing.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

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

❓
5
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