DEV Community

Arun Kumar
Arun Kumar

Posted on

Introduction to Java Exception Handling

What is Exception Handling?

Exception Handling in Java is a mechanism to handle runtime errors so that the normal flow of the program can be maintained.

An exception is an unwanted or unexpected event that occurs during program execution and disrupts the normal flow of instructions.


Why Exception Handling is Important?

  • Prevents program from crashing
  • Maintains normal flow of application
  • Helps in debugging errors easily

Basic Keywords in Exception Handling

  • try → block where code is written
  • catch → handles the exception

simple Example Program

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

        try {
            int a = 10;
            int b = 0;

            int result = a / b; // Exception occurs here

            System.out.println(result);
        } 
        catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)