[SalesForce] Put all the code in the try catch block

A helper class will throw a custom exception and which has complex logic. I need to catch this exception when invoking it, so I call this helper class in the try block.

I want to ask, is that OK if I put a lot of code in the try block?

Best Answer

It's ok, but you'll have less granular error handling. i.e. say you want to insert an account, and whether that fails or not you want to insert a contact, having them both in the same block would not allow that:

try
{
  insert account;
  insert contact;
}
catch (Exception e)
{
  // error handling
}

By using separate blocks you can try the contact regardless of whether the account worked:

try
{
  insert account;
}
catch (Exception e)
{
  // handle account error, e.g.:
  contact.Account = someDefaultAccountId;
}

try
{
  insert contact;
}
catch (Exception e)
{
  // handle contact errors
}

At the end of the day it depends on what level of error handling you want to do, generally with a transaction-style interface like VF controllers etc. I find that most things are all or nothing and do find myself using larger blocks.