PROGRAM 9:
Develop a JAVA program to raise a custom exception (user defined
exception) for DivisionByZero using try, catch, throw and finally.
Step 1: Open Eclipse
• Open Eclipse IDE
• Click File → New → Java Project
• Project Name: Employee
• Click Finish
Step 2: Create a Package
• In Project Explorer
• Right-click on src
• Click New → Package
• Package name:
employee
• Click Finish
Step 3: Create Java Class
• Right-click on employee package
• Click New → Class
• Class Name:
Point
• Tick public static void main(String[] args)
• Click Finish
Step 4: Write the Program Code
Copy and paste the complete code below inside [Link]:
package employee;
// User-defined exception class
class DivideByZeroException extends Exception {
public DivideByZeroException(String message) {
super(message);
}
}
public class Point {
public static void main(String[] args) {
int numerator = 15;
int denominator = 2; // change to 0 to test exception
try {
if (denominator == 0) {
throw new DivideByZeroException(
"Error: Cannot divide a number by zero.");
}
int result = numerator / denominator;
[Link]("Result: " + result);
} catch (DivideByZeroException e) {
[Link]([Link]());
} finally {
[Link]("I am in final block");
}
}
}
Step 5: Run the Program
• Right-click on [Link]
• Click Run As → Java Application
PART B: Output
Output 1 (Normal Execution)
If:
int denominator = 2;
Result: 7
I am in final block
Output 2 (Exception Case)
If:
int denominator = 0;
Error: Cannot divide a number by zero.
I am in final block