DEV Community

SILAMBARASAN A
SILAMBARASAN A

Posted on

exception in Java

In Java, an exception is an unexpected event that occurs during program execution and interrupts the normal flow of the program.

When an exception occurs, Java creates an object that contains information about the error. This object is called an Exception Object.

Instead of terminating the program immediately, Java provides a mechanism called Exception Handling to manage these situations gracefully.

public class Main {
    public static void main(String[] args) {

        int a = 10;
        int b = 0;

        int result = a / b;

        System.out.println(result);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output
Exception in thread "main" java.lang.ArithmeticException: / by zero

try and catch

The risky code is written inside the try block, and the exception is handled inside the catch block.

public class Main {
    public static void main(String[] args) {

        int a = 10;
        int b = 0;

        try {
            int result = a / b;
            System.out.println(result);
        }

        catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero");
        }

        System.out.println("Program continues...");
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Cannot divide by zero
Program continues...

Top comments (0)