Java Exercise
In this exercise, you will create a Java program that implements exception handling using try
, catch
, and finally
. You will learn how to handle runtime errors, preventing the program from stopping unexpectedly.
Instructions:
- Prompt the user to enter two integers.
- Perform division between the two numbers.
- Use a
try-catch
block to handle exceptions if the divisor is zero.
- In the
catch
block, display an error message if division by zero occurs.
- Use a
finally
block to display a message indicating that execution has completed.
- Compile and run the program to verify that it works correctly.
This exercise will help you understand how to handle exceptions in Java to make your programs more robust and resistant to unexpected errors.
View Example Code
import java.util.Scanner;
public class ExceptionHandling {
public static void main(String[] args) {
// Create a Scanner object for user input
Scanner scanner = new Scanner(System.in);
try {
// Ask the user to enter two numbers
System.out.print("Enter the numerator: ");
int numerator = scanner.nextInt();
System.out.print("Enter the denominator: ");
int denominator = scanner.nextInt();
// Perform the division and display the result
int result = numerator / denominator;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
// Catch and handle the exception if the denominator is 0
System.out.println("Error: Cannot divide by zero.");
} finally {
// Message that always executes
System.out.println("Execution finished.");
}
// Close the Scanner
scanner.close();
}
}
Output:
Enter the numerator: 10
Enter the denominator: 2
Result: 5
Execution complete.
Output with Exception:
Enter numerator: 10
Enter denominator: 0
Error: Cannot divide by zero.
Execution terminated.
This program demonstrates how to handle exceptions in Java using try-catch
to prevent errors when dividing by zero, and finally
to execute closing code regardless of whether an exception occurs.