Exception Handling Programs
Practicing exception handling scenarios builds confidence in writing safe, robust code that doesn't crash unexpectedly on bad input or unusual conditions.
Why practice these?
Practicing exception handling scenarios builds confidence in writing safe, robust code that doesn't crash unexpectedly on bad input or unusual conditions.
Program 1: Handle Division by Zero Safely
javaimport java.util.Scanner; public class SafeDivision { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter numerator: "); int a = sc.nextInt(); System.out.print("Enter denominator: "); int b = sc.nextInt(); try { System.out.println("Result: " + (a / b)); } catch (ArithmeticException e) { System.out.println("Error: Cannot divide by zero."); } } }
Output (when denominator entered is 0):
Enter numerator: 10
Enter denominator: 0
Error: Cannot divide by zero.Program 2: Custom Exception for Invalid Age
javaclass InvalidAgeException extends Exception { InvalidAgeException(String message) { super(message); } } public class AgeValidation { static void validateAge(int age) throws InvalidAgeException { if (age < 0 || age > 120) { throw new InvalidAgeException("Age must be between 0 and 120"); } System.out.println("Valid age: " + age); } public static void main(String[] args) { try { validateAge(150); } catch (InvalidAgeException e) { System.out.println("Error: " + e.getMessage()); } } }
Output:
Error: Age must be between 0 and 120Key Points to Remember
- Always validate user input before processing it, especially for values that could cause runtime exceptions.
- Custom exceptions make error messages clearer and more specific to your application's actual rules.
- Practicing multiple
catchblocks for different exception types builds confidence in handling varied error scenarios.