Introduction • Errors andexceptions are common during program execution. • Error → Irrecoverable (e.g., OutOfMemoryError). • Exception → Conditions that a program can handle (e.g., division by zero).
3.
What is anException? • An exception is an event that disrupts the normal flow of a program. • Occurs during runtime. • Example: int a = 10 / 0; // ArithmeticException
Keywords in ExceptionHandling • try → Defines block of code to be tested. • catch → Handles the exception. • finally → Executes code always (cleanup code). • throw → Used to throw an exception. • throws → Declares exceptions a method can throw.
6.
Try-Catch Example • try{ • int a = 10 / 0; • } catch (ArithmeticException e) { • System.out.println("Error: Division by zero!"); • }
Throw and Throws •void checkAge(int age) throws ArithmeticException { • if(age < 18) { • throw new ArithmeticException("Not eligible to vote"); • } • }
10.
Types of Exceptions •Checked Exceptions → Checked at compile time (e.g., IOException). • Unchecked Exceptions → Checked at runtime (e.g., NullPointerException). • Errors → Beyond programmer’s control (e.g., OutOfMemoryError).
11.
Benefits of ExceptionHandling • Separates error-handling code from normal code. • Improves program reliability. • Provides meaningful messages to users.