简体   繁体   中英

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?

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
}
try
{
    if(Policy!=null)
    {
        ...
    }
    else
    {
        throw new PolicyMissingExc(“Policy missing”);
    }
}
catch(PolicyMissingExc e)
{
  e.printstacktrace();
}
catch(PolicyExpired e)
{
  e.printstacktrace();
}
catch(SettlementException e)
{
  e.printstacktrace();
}

You can catch multiple exceptions but remember catch block must be in order from subclass to superclass otherwise you will get Unreachable catch block compilation error.

为什么不只有一个异常类SettlementException,并将其用作所有已知问题的容器(Set?)?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM