DEV Community

S Sarumathi
S Sarumathi

Posted on

Exception In Java

An Exception is an unwanted event that occurs during program execution and disrupts the normal flow of the program.

Program:

class Demo {

    public static void main(String[] args) {

        int a = 10;
        int b = 0;

        System.out.println(a / b);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Why Exceptions Occur?

  • Dividing a number by zero

  • Accessing an invalid array index

  • Opening a file that does not exist

  • Null object access

Handling Exceptions:

class Demo {

    public static void main(String[] args) {

        try {
            int a = 10;
            int b = 0;
            System.out.println(a / b);
        }
        catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Top comments (0)