Exception
An exception is an unexpected problem that occurs while a program is running, disrupting its normal flow — like trying to divide a number by zero, or accessing an array index that doesn't exist.
1. What is an Exception?
An exception is an unexpected problem that occurs while a program is running, disrupting its normal flow — like trying to divide a number by zero, or accessing an array index that doesn't exist.
2. Why is it used?
Java's exception mechanism allows a program to detect these problems and respond to them gracefully, instead of crashing suddenly and unpredictably.
3. Real-Life Example
Think of a fire alarm system in a building. When something unexpected (a fire) happens, the alarm system reacts in an organized way (alerting people, triggering sprinklers) instead of the building simply collapsing without warning.
4. Syntax
java// An exception is thrown automatically or manually throw new ExceptionType("message");
5. Example Program
javapublic class ExceptionDemo { public static void main(String[] args) { int[] numbers = {1, 2, 3}; System.out.println(numbers[5]); // causes an exception } }
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 36. Key Points to Remember
- Exceptions represent problems detected during program execution (runtime), not while writing the code.
- If not handled, an exception stops the program and prints an error trace.
- Java exceptions are objects, all ultimately based on the
Throwableclass.