Exception Handling in Java
• From Basics to Custom Exceptions
• Presented by: Your Name
What is an Exception?
• • Unexpected event disrupting program flow
• • Examples: division by zero, invalid index
• • Java provides structured handling
Why Exception Handling?
• • Avoids crashes
• • User-friendly error messages
• • Helps debugging
• • Maintains flow
Exception Handling Keywords
• • try → risky code
• • catch → handle error
• • finally → always runs
• • throw → manually throw
• • throws → declare exception
Basic try–catch Example
• try {
• int a = 10 / 0;
• } catch (ArithmeticException e) {
• [Link]("Cannot divide by zero");
• }
Multiple catch & finally
• try {
• int arr[] = new int[3];
• arr[5] = 50;
• }
• catch (ArrayIndexOutOfBoundsException e) {
• [Link]("Invalid index");
• }
• finally {
• [Link]("Always runs");
• }
throw vs throws
• • throw → used inside method
• • throws → used in method declaration
• void checkAge(int age) throws Exception {
• if(age < 18) throw new Exception("Not eligible");
• }
Custom Exception
• class InvalidAmountException extends Exception {
• InvalidAmountException(String msg) {
• super(msg);
• }
• }
Using Custom Exception
• if(amount < 0) {
• throw new InvalidAmountException("Amount cannot be
negative");
• }
Summary
• • Exceptions occur at runtime
• • try, catch, finally, throw, throws
• • Custom exceptions
• • Helps build stable applications