Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java ReferenceJava Reference1

Java try-catch Block
Handling Exceptions



In real-world programming, not everything goes as planned. Files might be missing, users might enter invalid input, or network calls might fail. In Java, rather than allowing your program to crash, you can use try-catch blocks to gracefully handle exceptions.

What is a try-catch Block?

The try-catch block is Java's way of saying: "Try this risky thing, and if it fails, here's what to do." It helps you prevent unexpected termination of your program by catching exceptions and letting you handle them in a user-friendly way.

Syntax of try-catch

try {
    // Code that may throw an exception
} catch (ExceptionType e) {
    // Code to handle the exception
}

Example: Divide by Zero

This is one of the most common runtime exceptions. Let’s see how try-catch can help handle it:

public class TryCatchExample {
    public static void main(String[] args) {
        int a = 10;
        int b = 0;

        try {
            int result = a / b;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero!");
        }

        System.out.println("Program continues...");
    }
}
Cannot divide by zero!
Program continues...

Explanation:

The division a / b throws an ArithmeticException because b is 0. Without the try-catch, the program would crash. But thanks to the catch block, we handle it and continue execution.

Multiple catch Blocks

Sometimes, more than one type of exception might occur. You can handle each differently:

public class MultipleCatchExample {
    public static void main(String[] args) {
        try {
            int[] arr = new int[3];
            arr[5] = 100 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Arithmetic error occurred.");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index is out of bounds.");
        } catch (Exception e) {
            System.out.println("General exception caught.");
        }
    }
}
Array index is out of bounds.

Why the Order of catch Blocks Matters

Java checks the catch blocks in the order they are written. If you place a general Exception block before specific exceptions like ArithmeticException or ArrayIndexOutOfBoundsException, the specific ones will never be reached, causing a compilation error.

Using Exception Object

You can get more details about what went wrong by printing the exception object:

public class ExceptionMessageExample {
    public static void main(String[] args) {
        try {
            String str = null;
            System.out.println(str.length());
        } catch (NullPointerException e) {
            System.out.println("Exception: " + e);
            e.printStackTrace();
        }
    }
}
Exception: java.lang.NullPointerException
java.lang.NullPointerException
    at ExceptionMessageExample.main(...)

Best Practices for try-catch

Real-Life Use Case: File Handling

Imagine trying to read from a file that doesn’t exist:

import java.io.*;

public class FileExample {
    public static void main(String[] args) {
        try {
            FileReader reader = new FileReader("nonexistent.txt");
            reader.read();
            reader.close();
        } catch (FileNotFoundException e) {
            System.out.println("File not found.");
        } catch (IOException e) {
            System.out.println("Error reading the file.");
        }
    }
}
File not found.

Conclusion

The try-catch block is your first line of defense against unpredictable runtime errors. It's not just about avoiding crashes; it's about writing robust, user-friendly Java applications that fail gracefully — or, better yet, recover intelligently.

QUIZ

Question 1:What happens when an exception is thrown inside a try block and there is no matching catch block provided?

Question 2:Placing a general catch (Exception e) block before specific ones like catch (ArithmeticException e) leads to a compile-time error.

Question 3:Which output will be produced by the following Java code?
try {
    int[] arr = new int[2];
    arr[4] = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Arithmetic exception occurred.");
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Index out of bounds.");
}

Question 4:Which of the following are considered good practices when using try-catch blocks?

Question 5:try-catch blocks can be used to handle both checked and unchecked exceptions in Java.

Question 6:Which line in the following code will throw a NullPointerException?
try {
    String str = null;
    System.out.println(str.length());
} catch (NullPointerException e) {
    System.out.println("Caught a null pointer!");
}



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M