Bhavna
Bhavna

Reputation: 115

Throwing Multiple Exceptions

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

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?

Upvotes: 0

Views: 297

Answers (3)

Solomon Slow
Solomon Slow

Reputation: 27115

Why not have just one exception class, SettlementException, and use it as a container (Set?) for all of the known problems?

Upvotes: 0

Ankush
Ankush

Reputation: 685

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.

Upvotes: 0

jbutler483
jbutler483

Reputation: 24549

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
}

Upvotes: 1

Related Questions