Interfaces for Custom Exceptions in Java


Create a Java program to demonstrate the use of an interface for a custom exception

  • MyException is a custom exception class that extends Exception. It has a constructor to set the exception message.
  • ExceptionLogger is an interface with a single method logException(Exception e), which is responsible for logging exceptions.
  • Logger is a class that implements the ExceptionLogger interface. It provides an implementation for the logException method to print the exception message.
  • In the Main class, an instance of Logger is created and assigned to the ExceptionLogger interface.
  • Inside the try-catch block, a MyException is thrown with a custom message. When the exception is caught, the logException method of the logger object is called to log the exception message.

Source Code

class MyException extends Exception
{
	public MyException(String message)
	{
		super(message);
	}
}
 
interface ExceptionLogger
{
	void logException(Exception e);
}
 
class Logger implements ExceptionLogger
{
	@Override
	public void logException(Exception e)
	{
		System.out.println("Logging Exception : " + e.getMessage());
	}
}
 
public class Main
{
	public static void main(String[] args)
	{
		ExceptionLogger logger = new Logger();
		try
		{
			throw new MyException("Custom Exception");
		} catch (Exception e)
		{
			logger.logException(e);
		}
	}
}

Output

Logging Exception : Custom Exception

Example Programs