9

I'm looking to check what type of exception is retruned in the following code snippet. I'm not sure exactly how to do it though, or if it's even possible.

try {
    //SOME LOGIC
} catch (exception ex) {
    System.debug(//EXCEPTION TYPE);
}

Would anyone have any suggestions or advice??

1 Answer 1

10

There is a getTypeName() method on the Exception class that you can use. It will output the actual instance's type.

Example 1:

try {
    //SOME LOGIC
} catch (Exception ex) {
    System.debug(ex.getTypeName()); 
}

Example 2:

Exception e = new MyCustomException();
System.debug(e.getTypeName()); 
// outputs 'MyCustomException', not 'Exception'.
3
  • 6
    Can also make use of 'e instanceof DmlException' etc Commented Jul 9, 2014 at 14:32
  • 5
    You can also catch specific exceptions, as in catch(DmlException e) { ... } catch(NoAccessException e) { ... } ...
    – sfdcfox
    Commented Jul 9, 2014 at 14:40
  • Excellent, cheers guys!
    – Daft
    Commented Jul 10, 2014 at 9:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .