Exception Handling in Salesforce

Exception Handling in Salesforce

I always had this bad feeling, that I wasn’t following the best practices handling exceptions in Apex. In most of the cases, I wasn’t doing any exception handling.

What is an exception?

An exception is a condition which changes the normal flow of program execution.That is when something bad happens which the program can’t handle during execution.Exception are the apex way of throwing up its hands and saying “I can not deal with this, you need to handle it”

What are conditions which result into exception?

  • Your code expects a value from something which is currently Null.
  • An insert or update falis because of the failure of custom validation rule which you have set up.
  • Assigning a query which returns no records or more than one record to a singleton sObject variable.
  • Accessing a list index which is out of bounds.

In all the above situations we are trying something which apex consider it impossible and an exception is thrown. Apex has 20 different types of exceptions.But all these exceptions are subclassed from a generic exception class.All the exception support standard methods for accessing the error message and the exception type.

What happens when an exception ocurrs?

When an exception occurs and you haven’t written the code to deal with it, it is called ‘unhandled’. An unhandled exception brings processing to a halt. If the code
which has processed so far contained any DML statements (Database Manipulation language), those statements will be rolled back completely.

When the exception occurs, the system notifies the running User of the problem. If you run into an exception in the apex code while using the standard salesforce UI, a red text message will appear on top of your screen displaying the text of the unhandled exception.

If the exception occurred due to the failure of custom field validation error and you’ve selected ‘next to the field’, then the exception message will appear next to the field in red color.

The system will notify the developer of the code in question that there has been a unhandled exception. An email will be sent to the developer with the Organization Id and User ID of the running user, as well as the exception message.

How do I catch exceptions?

Apex allows you tp handle your exception and write code to recover from an error. Apex uses try, other programming languagecother programming languages). You write your code inside the “try” block and if an exception occurred then you “catch” it and can run some code and “finally” you run some code whether you had an exception or not.

You have multiple catch blocks to catch any of the 20 different kinds of exception.

[sourcecode lang=”Java”]
//Your code here
} catch (ListException e) {
//Optional catch of a specific exception type
//Specific exception handling code here
} catch (Exception e) {
//Generic exception handling code here
} finally {
//optional finally block
//code to run whether there is an exception or not


An exception can occur in DML statements. For example, if you try to insert a record without providing the value for a required field. The addError() method can be called on a record or field and it will prevent the DML operation from committing.

For example:

[sourcecode lang=”Java”]
update accounts;
} catch (DMLException e){
for (Account account : accounts) {
account.addError(‘There was a problem updating the accounts’);
} finally {
inProgress = false;

If you have a custom controller or controller extension for a visualforce page you can handle exceptions just as in the example above.
To show the error on visualforce page, you can use ApexPages.message class to create a message for display.

[sourcecode lang=”HTML”]
ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL,’my error msg’);


Exception handling is a very important part of your application, and often it is overlooked. The good news is Apex makes it very easy to handle your own exceptions. Use try-catch-finally statements to catch system exceptions as they occur. Use custom exceptions to throw your own exception and adapt even when the system doesn’t object to program flow. These techniques will give better user experience.
You can keep the user aware of any errors you run into via Apex page messages in Visualforce and object .addError() messages in Apex triggers. if you want to be notified as the developer, you can write Apex email notifications or write your error to a custom object so you know when your code is misbehaving.
Apex has a robust framework for exception handling, start using it today in your triggers and classes.


This Post Has 63 Comments

  1. Feel confident in your favourite outfits thanks to our shapewear for women.Look and feel good with our collection of women’s shapewear. From bodysuits to shaping panties, shapewear will have you feeling amazing about how you look.No matter if you’re looking for a full body shaper or something else, it’s important to get one of the best shapewear garments. There are various reasons why women choose to wear shapewear.
    [url=https://www.esaning.com/]Shapewear & Plus Size Bodysuits[/url]

  2. Food Near Me

    Thanks for the terrific information for us.
    Best regards,
    Thompson Cannon

  3. Klaus

    Thank you for the auspicious writeup. It in fact was a entertainment
    account it. Glance advanced to more introduced agreeable from you!
    However, how can we keep in touch?

  4. Bars Near Me

    Very very good job and thanks for sharing such a blog.

    King regards,
    Boswell Cannon

  5. Thank you for the auspicious writeup. It in truth was once a enjoyment account it.
    Look complicated to far delivered agreeable from you! However, how can we keep up a correspondence?

  6. Hello! This is my 1st comment here so I just wanted to give a quick shout
    out and say I really enjoy reading your posts. Can you recommend any other blogs/websites/forums that go over the same topics?
    Thanks for your time!

  7. Does your blog have a contact page? I’m having
    trouble locating it but, I’d like to send you an email.
    I’ve got some creative ideas for your blog you might
    be interested in hearing. Either way, great blog and I look
    forward to seeing it expand over time.

  8. ufa

    Why viewers still use to read news papers when in this technological globe everything is
    accessible on web?

  9. Just wish to say your article is as astonishing. The clearness in your post is just spectacular and that i could think
    you’re an expert on this subject. Fine along with your permission allow me to
    take hold of your feed to stay updated with imminent post.
    Thanks one million and please continue the rewarding work.

  10. Can I just say what a reduction to find somebody who truly is aware of what theyre speaking about on the internet. You definitely know the way to bring an issue to gentle and make it important. More folks must read this and understand this side of the story. I cant consider youre no more standard since you undoubtedly have the gift.

  11. Bonjour On dirait que les thèmes de ce concis debrieffing requierent d’avantage de valeurs; Votre tournure peut paraitre recevable or je ne defend pas les différents avis plus anciens! il faudrait ajouter quelques valeurs pour plus de professionalisme! Merci

  12. Wow, superb blog layout! How lengthy have you ever been blogging for? you make blogging glance easy. The whole glance of your website is fantastic, well the content material!

  13. Latashia

    Ahaa, its fastidious discussion on the topic of this piece of writing here at this blog, I
    have read all that, so at this time me also commenting here.

  14. What’s Going down i’m new to this, I stumbled upon this I’ve discovered It positively helpful and it has helped
    me out loads. I am hoping to contribute & assist different users like its aided me.
    Great job.

  15. click here now

    Hello! I simply want to offer you a huge thumbs
    up for your great information you have here on this post.
    I am returning to your website for more soon.

  16. Lawrence

    Quality posts is the important to attract the people to visit the site, that’s what this web page is

  17. 스포츠토토

    You actually make it seem really easy along with your presentation however I to find this matter to be really
    something which I think I would by no means understand.
    It sort of feels too complex and extremely large for me.
    I am having a look forward to your subsequent put up, I will attempt
    to get the cling of it!

  18. camo phone case

    Hey are using WordPress for your site platform? I’m new to the blog world but I’m trying to get started and set up my own. Do you need any coding knowledge to make your own blog? Any help would be really appreciated!|

  19. I’ve been exploring for a bit for any high-quality articles or blogg posts on this kind
    of area . Exploring in Yahoo I finally stumbled upon this web site.
    Reading this info So i’m satisfied to express that I have a very good uncanny feeling I discovered
    just what I needed. I most no doubt willl make sure to do noot omit this site and gibe it a glance
    on a continuing basis.

  20. Agen Slot

    Hey There. I found your blog using msn. That is an extremely neatly
    written article. I’ll make sure to bookmark it and return to read more of your helpful info.
    Thank you for the post. I’ll certainly comeback.

  21. Landon

    Hi there, I enjoy reading through your article. I wanted to
    write a little comment to support you.

  22. the feed

    Great article! We will be linking to this great post on our site. Keep up the good writing.|

  23. I am really impressed with your writing skills and also with the layout on your blog.

    Is this a paid theme or did you modify it yourself?
    Anyway keep up the excellent quality writing, it’s rare
    to see a great blog like this one nowadays.

  24. Russel

    What you said made a ton of sense. But, what about this?
    suppose you were to create a awesome post title?
    I ain’t saying your content is not solid, but what if you added something
    to possibly grab people’s attention? I mean Exception Handling in Salesforce
    | MyTutorialRack is a little vanilla. You could glance at Yahoo’s
    front page and note how they create post titles to grab people to click.
    You might try adding a video or a picture or two to grab people interested about what you’ve got to say.

    In my opinion, it might bring your posts a little bit more interesting.

  25. feed

    Thank you for the auspicious writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! However, how could we communicate?|

  26. the feed

    Thanks for the good writeup. It in truth used to be a entertainment account it. Look advanced to more added agreeable from you! By the way, how can we communicate?|

  27. Alena Toomey

    Good post and a nice summation of the problem. My only problem with the analysis is given that much of the population joined the chorus of deregulatory mythology, given vested interest is inclined toward perpetuation of the current system and given a lack of a popular cheerleader for your arguments, I’m not seeing much in the way of change.

  28. thefeed

    Very energetic post, I liked that bit. Will there be a part 2?|

  29. Hi there, I read your blogs regularly. Your writing style is awesome, keep
    up the good work!

  30. If you are going for best contents like I do, simply pay a visit this site everyday as it gives quality contents, thanks

  31. Earlene

    Hello! This is my first comment here so I just wanted to give a quick shout out and
    say I genuinely enjoy reading through your articles.

    Can you recommend any other blogs/websites/forums that go over
    the same topics? Appreciate it!

  32. Miranda

    It’s really a great and useful piece of info. I’m satisfied that you simply shared this helpful info with
    us. Please stay us up to date like this. Thanks for sharing.

  33. Tyrone Oeftger

    Thank you for sharing excellent informations. Your site is very cool. I am impressed by the details that you’ve on this blog. It reveals how nicely you understand this subject. Bookmarked this website page, will come back for extra articles. You, my pal, ROCK! I found just the info I already searched all over the place and simply couldn’t come across. What a great web-site.

  34. Elias

    each time i used to read smaller articles which also clear their motive, and that is also happening with this post which I am reading at this

  35. Natalia

    Fantastic goods from you, man. I have understand your stuff previous to
    and you’re just extremely excellent. I actually like what you’ve
    acquired here, really like what you’re saying and the way in which you say it.
    You make it enjoyable and you still take care of to keep it
    smart. I can not wait to read much more from you. This is really
    a terrific web site.

  36. C++ IDE

    Quality content is the crucial to be a focus for the people to go to see
    the web page, that’s what this web page is providing.

  37. relx

    When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get four e-mails with the same comment.
    Is there any way you can remove people from that service?

  38. Melvin

    Hello would you mind letting me know which webhost you’re using?
    I’ve loaded your blog in 3 different internet browsers and
    I must say this blog loads a lot quicker then most.
    Can you suggest a good internet hosting provider at a honest price?
    Thanks, I appreciate it!

  39. Vicente

    I was suggested this website via my cousin. I am no longer positive whether this post
    is written by him as no one else recognise such targeted
    about my trouble. You’re amazing! Thank you!

  40. Lavern

    whoah this blog is great i like studying your posts.
    Keep up the great work! You understand, many people are searching round for this
    info, you could aid them greatly.

  41. XMLTV epg

    Hi there! This article could not be written much better! Looking at this article reminds me of my previous
    roommate! He continually kept talking about this. I’ll send this post to him.
    Fairly certain he’ll have a very good read. Many thanks
    for sharing!

  42. Bill

    Hello, I enjoy reading through your post. I like to write a little comment to support you.

  43. Belinda

    It is the best time to make some plans for the future and it is time to be
    happy. I’ve read this post and if I could I desire
    to suggest you few interesting things or suggestions.
    Perhaps you could write next articles referring to this article.
    I desire to read more things about it!

  44. Shawnee

    Thanks for ones marvelous posting! I really enjoyed reading it, you’re a great author.I will be sure to bookmark your blog and definitely will come back someday.
    I want to encourage you continue your great job, have a nice holiday weekend!

  45. Tommie

    I really like it whenever people come together and
    share opinions. Great blog, keep it up!

  46. czytaj tu

    Heya i am for the first time here. I came across this board and I in finding It really useful & it helped me out
    much. I hope to present something back and aid others such as
    you aided me.

  47. Jorja

    Does your site have a contact page? I’m having trouble
    locating it but, I’d like to shoot you an e-mail. I’ve got some ideas for your blog you might be interested in hearing.
    Either way, great site and I look forward to seeing it develop over time.

  48. Rhonda

    Hurrah, that’s what I was looking for, what a
    data! existing here at this blog, thanks admin of this site.

  49. Does your website have a contact page? I’m having a tough time locating it but,
    I’d like to shoot you an e-mail. I’ve got some suggestions for
    your blog you might be interested in hearing. Either way, great site and I look forward to seeing it expand over time.

  50. Jermaine

    Howdy would you mind letting me know which web host you’re utilizing?

    I’ve loaded your blog in 3 different internet browsers and I must say this
    blog loads a lot quicker then most. Can you suggest a good
    internet hosting provider at a fair price? Thank you, I appreciate it!

  51. Marshall

    I don’t even understand how I stopped up right here, however I thought this submit was good.
    I don’t recognise who you are but certainly you are going to
    a famous blogger when you are not already. Cheers!

Leave a Reply