Exception Handling
Exception Handling
try {
System.out.println(arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid array index accessed.");
}
}
}
try {
int num = Integer.parseInt(input);
System.out.println("Number: " + num);
} catch (NumberFormatException e) {
System.out.println("Invalid number format.");
}
}
}
try {
System.out.println(str.length());
} catch (NullPointerException e) {
System.out.println("Cannot access method on a null object.");
}
}
}
Scenario: Handling Different Exceptions in a Single Program (try with multiple catch)
try {
// This line will throw a NullPointerException
System.out.println("String length: " + str.length());
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException: String is null.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: Invalid array index.");
} catch (Exception e) {
System.out.println("Caught General Exception: " + e.getMessage());
}
System.out.println("Program continues...");
}
}
try {
System.out.print("Enter a number: ");
int number = Integer.parseInt(scanner.nextLine());
System.out.println("You entered: " + number);
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid number.");
} finally {
scanner.close();
System.out.println("Scanner closed. This block always runs.");
}
System.out.println("Program continues...");
}
}
Scenario: Validate Age for Voting using Throw
public class ThrowExample {
public static void checkAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or older to vote.");
} else {
System.out.println("You are eligible to vote.");
}
}
System.out.println("Program continues...");
}
}
try {
account.withdraw(6000); // This will trigger the exception
} catch (InsufficientFundsException e) {
System.out.println("Exception caught: " + e.getMessage());
} finally {
System.out.println("Transaction attempt finished.");
}
}
}
try {
reg.registerUser("abc"); // Will throw custom unchecked exception
} catch (InvalidUsernameException e) {
System.out.println("Exception caught: " + e.getMessage());
} finally {
System.out.println("Registration attempt complete.");
}
}
}