Given the following code, what does the developer expect will cause block C to execute:

      //code block A
      //code block B
      //code block C
  • Some code which is in first Try but not in second Try and which can throw error. Or something in inner catch block which can throw error. To be specific some thing in code block B which can throw error will be catched by outer catch i suppose.
    – Mr.Frodo
    Jun 21, 2018 at 15:59

1 Answer 1


Typically, you would use try-catch inside another because you don't want to exit the entire try-catch block because of a (possibly expected) error. For example, I once wrote code that looked like this:

try {
  // some logic here //
  try {
    // do some queries here //
  } catch(QueryException e) {
    // It's okay that the query failed //
  // more logic here
} catch(Exception e) {
  // something *else* happened that was unexpected //

In this case, we want to continue if, and only if, there's a QueryException where we expect we might get one, but for any other exception, we want to abort immediately. It's rare to need this design, and I would avoid it at all costs, but can can be useful in certain controlled situations.

The three most likely scenarios where you might want to use this pattern is for a QueryException, DMLException, and CalloutException, especially the latter, since there are some exceptions thrown that you could recover from gracefully, but you still want to protect yourself against other unexpected issues. I could arguably see cases for something like StringException as well, perhaps to protect against malformed XML/JSON.

Note that sometimes novice developers really don't understand the purpose of try-catch, so this could also possibly be an overengineered solution. I've seen that entirely too often in code written by inexperienced developers, because they don't know enough about the language/logic to write the code in a clearer way. As one gains experience with programming in Apex, they should naturally end up using try-catch less often as they gain confidence about how the platform runs.

  • Great example. In the code I’m looking at, the catch blocks are both for generic Exceptions.
    – snugsfbay
    Jun 21, 2018 at 16:27
  • 1
    @snugsfbay That's almost certainly a "novice developer" code block. I'd consider revising it if possible.
    – sfdcfox
    Jun 21, 2018 at 16:34
  • Thanks, I was planning to remove the code, just wanted to see if I had missed a real reason for it.
    – snugsfbay
    Jun 21, 2018 at 17:00

You must log in to answer this question.

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