Find your content:

Search form

You are here

Put all the code in the try catch block

 
Share

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?


Attribution to: Jair

Possible Suggestion/Solution #1

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.


Attribution to: Matt Lacey

Possible Suggestion/Solution #2

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.


Attribution to: cropredy
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/30258

My Block Status

My Block Content