Method Overloading with Methods That Have Different Exception Types in Java


Write a Java program to demonstrate method overloading with methods that have different exception types

  • In the Main class's main method, an instance of the Calculator class is created.
  • The divide method of the Calculator class is called twice, once with two integers and once with three integers.
  • The first call to calculator.divide(10, 2) invokes the method that divides two integers and prints the result.
  • The second call to calculator.divide(10, 5, 0) invokes the method that divides three integers, but since the third argument is 0, it throws an ArithmeticException for division by zero.
  • The catch block in the Main class catches the ArithmeticException, and it prints the exception message.

Source Code

public class Main
{
	public static void main(String[] args)
	{
		Calculator calculator = new Calculator();
		System.out.println("Result of division : " + calculator.divide(10, 2));
		try {
			System.out.println("Result of division (with exception) : " + calculator.divide(10, 5, 0));
		} catch (ArithmeticException e) {
			System.out.println("Exception : " + e.getMessage());
		}
	}
}
class Calculator
{
	int divide(int a, int b)
	{
		return a / b;
	}
 
	int divide(int a, int b, int c) throws ArithmeticException
	{
		if (c == 0)
		{
			throw new ArithmeticException("Division by zero");
		}
		return (a / b) / c;
	}
}

Output

Result of division : 5
Exception : Division by zero

Example Programs