Basic Exception Handling
Basic Exception Handling
import java.util.Scanner;
public class ExceptionHandlingExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
// Exception 1: Handling NumberFormatException
System.out.print("Enter an integer: ");
int num = Integer.parseInt(scanner.nextLine()); // Could throw NumberFormatException
} catch (NumberFormatException e) {
System.out.println("Error: Invalid number format! Please enter a valid integer.");
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Index out of bounds! Choose between 0 and 2.");
} finally {
System.out.println("Execution completed.");
scanner.close();
}
}
}