DEV Community

Harini
Harini

Posted on

Exception Handling in Java

What is an Exception?

An exception is an event that disrupts the normal execution of a program.

Example:

int a = 10 / 0;
Enter fullscreen mode Exit fullscreen mode

Output:

ArithmeticException

Here, dividing by zero causes an exception.

Exception Handling

Exception handling is a mechanism used to handle runtime errors so the program does not terminate suddenly.

It allows the program to continue execution normally.

Why Exception Handling is Used

Without exception handling:

  • Program stops immediately when an error occurs.

With exception handling:

  • Error can be handled properly.
  • Remaining code can continue executing.

Example:

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

        System.out.println("Start");

        int a = 10 / 0;

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

Output
Start
Exception in thread "main" java.lang.ArithmeticException

End will not execute.

try-catch in Java

  • try-catch is used to handle exceptions.

Syntax

try {
    // risky code
}
catch(ExceptionType e) {
    // handling code
}
Enter fullscreen mode Exit fullscreen mode

Example of try-catch

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

        try {
            int a = 10 / 0;
        }

        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

Real-Time Example

ATM application:

  • If wrong PIN is entered,program should show error message instead of stopping.

  • Banking apps, websites, and mobile apps use exception handling to avoid crashes.

Top comments (0)