Search code examples
javaexceptionextendscustom-exceptions

Throwing Multiple Exceptions


I have a Java Application code that has following custom Exception structure

  • SettlementException extends Exception
  • PolicyMissingException extends SettlementException
  • PolicyExpiredException extends SettlementException

I have some try/catch blocks in the code that try PolicyMissing and PolicyExpired and throw the same.

try
{
    if (Policy != null)
    {
        ...
    }
    else
    {
        throw new PolicyMissingException(“Policy missing”);
    }
}
catch(PolicyMissingException e)
{
  e.printstacktrace();
}

Is there any way I can throw SettlementException too besides PolicyMissing and PolicyExpired along with them?


Solution

  • The below code should allow you to catch all three exceptions, and do something with each one. Also note, the order of the 'catches' is important too (see comment below this post)

    try
    {
        if(Policy!=null)
        {
            ...
        }
        else
        {
            throw new PolicyMissingExc(“Policy missing”);
        }
    }
    catch(PolicyMissingExc e)
    {
      e.printstacktrace();
    }
    catch(PolicyExpired c)
    {
      //catch c here
    }
    catch(SettlementException b)
    {
      //catch b here
    }