Java Exceptions – Try…Catch
Handle a failure where you can do something useful.
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.
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.
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 Type | Checked? | Common cause | Example |
|---|---|---|---|
ArithmeticException | Unchecked | Division by zero | int x = 5 / 0; |
NullPointerException | Unchecked | Using a null reference | str.length() when str is null |
ArrayIndexOutOfBoundsException | Unchecked | Accessing invalid array index | arr[10] on a 5-element array |
NumberFormatException | Unchecked | Invalid string-to-number parse | Integer.parseInt("abc") |
IOException | Checked | File not found / read error | Reading a missing file |
throw vs throws
// 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.
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.
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.
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.
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.
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.