CH - 4 - Lab Exercise
CH - 4 - Lab Exercise
Problem:
Write a Java program that asks the user to enter two numbers and then divides the first number
by the second. Handle the following exceptions:
If the user enters a non-numeric value, catch it and display an error message.
If the user tries to divide by zero, catch the ArithmeticException and display a relevant
message.
If any other unexpected error occurs, catch it and display a general error message.
Solution:
Explanation:
try block: Contains the code that may throw exceptions. In this case, parsing input and
performing division.
catch blocks: Handle specific types of exceptions.
o NumberFormatException: This exception is thrown if the user enters a non-
numeric input (e.g., a string).
ArithmeticException: This exception is thrown when an arithmetic error occurs, such as dividing
by zero.
import java.util.Scanner;
try {
// Ask for user input
System.out.print("Enter the first number: ");
int num1 = Integer.parseInt(scanner.nextLine());
try {
// Ask the user to enter an index
System.out.print("Enter an index (0-4) to access an element in the array: ");
int index = Integer.parseInt(scanner.nextLine());
try {
System.out.print("Enter the path of the file to read: ");
String filePath = reader.readLine();