An exception is an unexpected event that occurs during program execution and disrupts the normal flow of the program.
For example:
int a = 10;
int b = 0;
int result = a / b;
This causes:
ArithmeticException
because division by zero is not allowed.
Other examples include trying to access an invalid array index or trying to use a null reference.
Exception handling allows us to handle errors gracefully instead of allowing the program to terminate unexpectedly.
Without handling:
int result = 10 / 0;
System.out.println("Hello");
The exception occurs and "Hello" won't execute normally.
With handling:
try {
int result = 10 / 0;
}
catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
The exception is handled and the program can continue.
Exception handling → detect, handle, and recover from exceptional situations.