[SalesForce] Try, try, catch, catch

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

try{
   try{
      //code block A
   }catch{
      //code block B
   }
}catch{
      //code block C
}

Best Answer

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.