0% found this document useful (0 votes)
2 views

Basic Exception Handling

The document is a Java program demonstrating exception handling with three types of exceptions: NumberFormatException, ArithmeticException, and ArrayIndexOutOfBoundsException. It prompts the user for an integer, a divisor, and an index to access an array, handling potential errors gracefully. The program ensures that resources are closed after execution, regardless of whether an exception occurred.

Uploaded by

jemuel lago
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Basic Exception Handling

The document is a Java program demonstrating exception handling with three types of exceptions: NumberFormatException, ArithmeticException, and ArrayIndexOutOfBoundsException. It prompts the user for an integer, a divisor, and an index to access an array, handling potential errors gracefully. The program ensures that resources are closed after execution, regardless of whether an exception occurred.

Uploaded by

jemuel lago
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

package Ricks;

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

// Exception 2: Handling ArithmeticException (division by zero)


System.out.print("Enter a divisor: ");
int divisor = Integer.parseInt(scanner.nextLine());
int result = num / divisor; // Could throw ArithmeticException
System.out.println("Result: " + result);

// Exception 3: Handling ArrayIndexOutOfBoundsException


int[] numbers = {1, 2, 3};
System.out.print("Enter an index to access (0-2): ");
int index = Integer.parseInt(scanner.nextLine());
System.out.println("Number at index: " + numbers[index]); // Could throw
ArrayIndexOutOfBoundsException

} 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();
}
}
}

You might also like