Method Overloading with Overloaded Methods That Use Different Parameter Types and Handle Exceptions in Java


Create a Java program to demonstrate method overloading with overloaded methods that use different parameter types and handle exceptions

  • In the main method of the OverloadingWithExceptionHandlingDemo class, an instance of the MethodOverloadingDemo class is created.
  • We call the divide method of the MethodOverloadingDemo class to perform division operations, both with integer and double arguments.
  • The divide method is overloaded to handle division operations for both integers and doubles.
  • In each overload of the divide method, it checks if the divisor is zero. If it is, it throws an IllegalArgumentException with an appropriate message.
  • When we attempt to divide by zero in the main method, an exception is thrown and caught, and the error message is printed to the standard error stream.

Source Code

public class OverloadingWithExceptionHandlingDemo
{
	public static void main(String[] args)
	{
		MethodOverloadingDemo calculator = new MethodOverloadingDemo();
 
		try {
			int intResult = calculator.divide(10, 2);
			double doubleResult = calculator.divide(7.5, 2.5);
 
			System.out.println("Result of integer division : " + intResult);
			System.out.println("Result of double division : " + doubleResult);
 
			// Attempt to divide by zero
			intResult = calculator.divide(5, 0); // This will throw an exception
		} catch (IllegalArgumentException e) {
			System.err.println("Exception : " + e.getMessage());
		}
	}
}
class MethodOverloadingDemo
{    
	int divide(int a, int b)// Method to divide two integers
	{
		if (b == 0)
		{
			throw new IllegalArgumentException("Cannot divide by zero");
		}
		return a / b;
	}
 
	double divide(double a, double b)// Method to divide two doubles
	{
		if (b == 0.0)
		{
			throw new IllegalArgumentException("Cannot divide by zero");
		}
		return a / b;
	}
}

Output

Result of integer division : 5
Result of double division : 3.0
Exception : Cannot divide by zero

Example Programs