[SalesForce] an elegant way to catch multiple exceptions without catching generic exceptions

I don't want to catch generic exceptions, but I want to handle all the exceptions I want to catch exactly the same way.

For arguments sake, lets say the code is:

try {
   doSomething();
}
catch(AException ex) {
   handleException();
}
catch(BException ex) {
   handleException();
}
catch(CException ex) {
   handleException();
}
/* ... */
catch(ZException ex) {
   handleException();
}

Is there an elegant way to express this?

I thought about creating a variable

Set<Type> exceptionsToHandle = new Set<Type>{
   AException.class, 
   BException.class, 
   CException.class, 
   /* ... */
   ZException.class 
}
try {
   doSomething();
}
catch(Exception ex) {
  if (exceptionsToHandle.contains(getType(ex)) {
       handleException();
  }
  else {
      throw ex;
  }
}

Except there is a fundamental problem: We have no way to actually get the exception's Type outside of ugly trial and error code which will be as inelegant as the problem I'm trying to solve.

Alternatively, I could make a set of strings and then check the class name for the instance of the Exception, but I'd rather have a typesafe solution.

Any ideas?

Best Answer

You can still support concrete types with getTypeName by using the Type.forName method.

Set<Type> allowlist = new Set<Type> { DmlException.class, ListException.class };
try
{
    // do stuff
}
catch (Exception pokemon)
{
    if (!allowlist.contains(Type.forName(pokemon.getTypeName()))
    {
        throw pokemon;
    }
    // actual error handling logic here
}
Related Topic