0
0
Javaprogramming~5 mins

Try–catch block in Java

Choose your learning style9 modes available
Introduction

A try-catch block helps your program handle errors without crashing. It lets you try some code and catch problems if they happen.

When reading a file that might not exist.
When dividing numbers and the divisor could be zero.
When converting text to numbers that might be wrong.
When working with network connections that can fail.
Syntax
Java
try {
    // code that might cause an error
} catch (ExceptionType name) {
    // code to handle the error
}

The try block contains code that might cause an error.

The catch block runs only if an error happens in the try block.

Examples
This catches a division by zero error and prints a message.
Java
try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero.");
}
This catches an error when trying to use a null text.
Java
try {
    String text = null;
    System.out.println(text.length());
} catch (NullPointerException e) {
    System.out.println("Text is null.");
}
Sample Program

This program tries to access an array element that does not exist. The catch block handles the error and the program keeps running.

Java
public class TryCatchExample {
    public static void main(String[] args) {
        try {
            int[] numbers = {1, 2, 3};
            System.out.println(numbers[5]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Oops! Index is out of range.");
        }
        System.out.println("Program continues smoothly.");
    }
}
OutputSuccess
Important Notes

You can have multiple catch blocks to handle different errors.

Try-catch blocks help keep your program from stopping unexpectedly.

Summary

Use try-catch to handle errors safely.

The try block runs code that might fail.

The catch block runs if an error happens, letting you respond nicely.