3

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?

2 Answers 2

7

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.

2
  • 1
    All-or-nothing behavior isn't really implied with a try-catch approach alone, but rather with transactions and rollbacks. Even if that's not the scope of the question, your last line somewhat hinted at it. (I know you know that, but others may not realize) Commented Mar 17, 2014 at 10:25
  • Thanks your reply. @LaceySnr To provide more detail for my questions, I am using Trigger Pattern for Tidy, Streamlined, Bulkified Triggers design to implement my triggers. Can I put the try catch to handle TriggerFactory.createHandler() exception in the AccountTrigger?
    – Jair
    Commented Mar 18, 2014 at 1:34
0

Similar to @LaceySnr (for whom I have great respect), my variation on this where the catch action is always the same is the following (assuming a VF controller):

String step;
try {
    step = 'Step 00 do account insert';
    insert account;
    step = 'Step 01 do Contact insert';
    contact.accountId = account.id;
}
catch (Exception e) {
    // do rollbacks or addError() as necessary
    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'[XX-nn] Account/Contact insertion ' + 
                       ' error at step: ' + step + '. ' + e.getMessage());
}

where [XX-nn] is from some programmer-managed list of error codes to assist tracing back a reported error to the code section. The step variable assists in diagnostics if the try block is doing many things (such as coordinating the updates of several SObjects or otherwise complex code that could be subject to error). Bottom line, I like to have lots of context in my error messages as my diagnostic time is precious.

You must log in to answer this question.

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