Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Visualforce Controller Bad Example with try/catch
// New account
Account a = new Account(Name = 'New Account');
try{
insert a;
system.debug('Success');
} catch(dmlexception e){
// If DML failed, ends up here
system.debug('Error inserting account: ' + e);
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Could not insert account record. Error: ' + e));
}
// ************ Assume that the account was a success above, continue below ***********
// New Case linked to account
Case c = new Case(subject = 'I need help', accountId = a.id);
try{
insert c;
system.debug('Success');
} catch(dmlexception e){
// ************ Assume the CASE insert FAILED ***********
// If DML failed, ends up here
system.debug('Error inserting case: ' + e);
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Could not insert Case record. Error: ' + e));
}
// If we get this far in code, something may have failed and been caught above, or everything worked.
system.debug('Potential Success');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment