Java Exceptions – Try…Catch

</>Coding Tamilan.← Java course & curriculum
Java Masterclass · Lesson 46 / 50 · English

Java Exceptions – Try…Catch

Handle a failure where you can do something useful.

Step-by-step explanationsRunnable JavaPractice + answer

Read this topic in தமிழ் ↗.

By the end of this lesson, you can…

  • Explain the key idea behind Exceptions – Try…Catch.
  • Read and run a complete example, then predict what changes.
  • Recognize the topic-specific mistake discussed below.
01 / The concept

Understand the idea

An exception transfers control when an operation cannot complete normally. Catch a specific type when you can recover, add context, or choose a fallback. Avoid empty catch blocks that hide failures and make debugging harder.

02 / Step by step

Explore the details

Java Exceptions

As mentioned in the Errors chapter, different types of errors can occur while running a program – such as coding mistakes, invalid input, or unexpected situations.

When an error occurs, Java will normally stop and generate an error message. The technical term for this is: Java will throw an exception (throw an error).

Exception Handling (try and catch)

Exception handling lets you catch and handle errors during runtime – so your program doesn't crash.

It uses different keywords:

The try statement allows you to define a block of code to be tested for errors while it is being executed.

The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

The try and catch keywords come in pairs:

Consider the following example:

If an error occurs, we can use try...catch to catch the error and execute some code to handle it:

Finally

The finally statement lets you execute code, after try...catch, regardless of the result:

The throw keyword

The throw statement allows you to create a custom error.

The throw statement is used together with an exception type. There are many exception types available in Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc:

If age was 20, you would not get an exception:

Errors and Exception Types

The table below shows some of the most common errors and exceptions in Java, with a short description of each:

Exception Hierarchy

Exception TypeChecked?Common causeExample
ArithmeticExceptionUncheckedDivision by zeroint x = 5 / 0;
NullPointerExceptionUncheckedUsing a null referencestr.length() when str is null
ArrayIndexOutOfBoundsExceptionUncheckedAccessing invalid array indexarr[10] on a 5-element array
NumberFormatExceptionUncheckedInvalid string-to-number parseInteger.parseInt("abc")
IOExceptionCheckedFile not found / read errorReading a missing file

throw vs throws

Java reference fragmentJAVA
// throw — explicitly throws an exception inside a method
void setAge(int age) {
    if (age < 0 || age > 150) {
        throw new IllegalArgumentException("Invalid age: " + age);
    }
    this.age = age;
}

// throws — declares that a method MAY throw a checked exception
void readFile(String path) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(path));
    System.out.println(reader.readLine());
    reader.close();    // caller must handle or re-declare IOException
}

// Multi-catch — handle multiple exception types at once (Java 7+)
try {
    int[] arr = new int[3];
    arr[10] = 1;
} catch (ArrayIndexOutOfBoundsException | NullPointerException e) {
    System.out.println("Caught: " + e.getMessage());
} finally {
    System.out.println("Always runs");
}

Best practices: Catch the most specific exception first (e.g., FileNotFoundException before IOException). Always close resources in finally — or better, use try-with-resources: try (var r = new FileReader("f.txt")) { ... } — it closes automatically.

Tip: For a list of all errors and exception types, go to our Java Errors and Exception Types Reference.

03 / Read and predict

A complete runnable example

This complete Main.java program focuses on the lesson idea. Reference fragments above may demonstrate individual statements; this example includes the imports, entry point, and supporting types it needs.

Main.java · complete runnable exampleJAVA
public class Main {
    public static void main(String[] args) throws Exception {
        try {
            int count = Integer.parseInt("not-a-number");
            System.out.println(count);
        } catch (NumberFormatException ex) {
            System.out.println("Please enter a whole number.");
        }
        System.out.println("Program continues.");
    }
}
Predict first. Then reveal the expected output / வெளியீடு
Please enter a whole number.
Program continues.

The output shown was checked by running this complete example. Trace the executed statements in order, then compare with your run.

04 / Learn by changing

Change it. Run it. Understand it.

Load this lesson example into the editor. Change one value or statement, predict the result, then press RUN to execute Java.

Open Java editor ↗
After the editor loads, choose Load this lesson example, then press RUN.

Powered by OneCompiler. Code you run is sent to OneCompiler for execution. For Scanner examples, supply input in the editor I/O panel; for file examples, files exist in its execution environment.

05 / Your turn

Make it your own

Practice challenge

Replace the input with 12 and predict whether the catch block runs.

Reveal the answer and reasoning / விடை

The catch block does not run. The program prints 12 and then Program continues.

One mistake to avoid: Do not catch Exception indiscriminately when a specific exception describes the failure you intend to handle.

Your learning checkpoint

  • Explain the example without reading the output first.
  • Make the change requested in the practice task.
  • Describe why the result changed—or why compilation failed.

Ready to move on? Follow the next lesson in course order, or return to the curriculum to review a prerequisite.

Coding Tamilan · Understand the idea. Try the code. Build the habit.