Handling Exceptions in Overloaded Methods

This program demonstrates handling exceptions in overloaded methods.

Problem Statement

Write a Java program where overloaded methods throw different exceptions.

Source Code

1 class Overloaded {
2 void risky(int x) throws Exception {
3 if(x==0) throw new Exception("Eduinq General Exception");
4 }
5 void risky(String s) {
6 try {
7 Integer.parseInt(s);
8 } catch(NumberFormatException e) {
9 System.out.println("Eduinq Exception: Invalid Number");
10 }
11 }
12 }
13 public class OverloadedExceptionExample {
14 public static void main(String[] args) {
15 System.out.println("Eduinq Overloaded Exception Example");
16 Overloaded o=new Overloaded();
17 try {
18 o.risky(0);
19 } catch(Exception e) {
20 System.out.println("Eduinq Exception: "+e.getMessage());
21 }
22 o.risky("abc");
23 }
24 }

Program Output

					Eduinq Overloaded Exception Example
Eduinq Exception: Eduinq General Exception
Eduinq Exception: Invalid Number
				

Explanation

Overloaded methods can throw different exceptions. - Caller must handle exceptions accordingly. - Improves flexibility and robustness. - In enterprise systems, overloaded exception handling ensures versatile APIs. Conclusion: Shows handling exceptions in overloaded methods.

Quick Links to Explore