Laboratory Activity – Exception Handling
CCPRGG2L – Intermediate Programming
Activity Title: Exception Handling in Java
Objectives:
The objective of this lab is to understand and implement exception handling in Java. Students will
learn how to use try, catch, finally, throw, and throws to handle exceptions effectively and write robust
programs.
Problem:
Task 1: Basic Exception Handling
Steps:
1. Create a Java program that accepts two integers from the user and performs division.
2. Use a try-catch block to handle the following exceptions:
o ArithmeticException (e.g., division by zero).
o InputMismatchException (e.g., invalid input).
3. Display appropriate error messages for each exception.
Task 2: Using Multiple Catch Blocks
Steps:
1. Modify the program in Task 1 to include multiple catch blocks to handle other potential exceptions,
such as NumberFormatException.
2. Add input validation to ensure only integers are processed.
Task 3: The finally Block
Steps:
1. Enhance the program from Task 2 by adding a finally block.
2. In the finally block, print a message: "Execution completed." This block should execute regardless
of whether an exception is thrown or not.
Task 4: Custom Exception
Steps:
1. Create a custom exception class called NegativeNumberException that extends
the Exception class.
2. Modify the program to throw a NegativeNumberException if any of the input numbers are negative.
3. Catch this exception and display an appropriate error message.
Task 5: Using throws Keyword
Steps:
1. Create a method called performDivision that takes two integers as arguments and performs division.
2. Use the throws keyword in the method signature to declare that the method may throw
an ArithmeticException.
3. Call this method from the main method and handle the exception using a try-catch block.
Post-Lab Questions:
1. What is the purpose of declaring exceptions using the throws keyword?
2. How does a custom exception differ from built-in exceptions?
3. Can a finally block execute without a catch block? Explain.
Submission Guidelines:
1. Submit your Java code files for all tasks.
2. Include a brief report (1-2 pages) describing the challenges you faced and how you resolved them.
3. Answer the post-lab questions. Write your answer in ½ crosswise paper.
Sample run for tasks 1 – 3
Sample run for task 4:
Sample run for task 5: