Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

When to use try catch statements

I'm a bit confused when to use a try catch statement, I know there are a lot of similar questions and I have checked a few and the information I seem to get with them is if else is faster, try catch is more expensive and I should use if else to catch errors if they are expected and try catch to catch unexpected errors, but my question is how do you prepare for something unexpected, because an expectation of a possible error would be required to a write code for one. I'm not sure I understand correctly what unexpected means in the context using a try catch statement. From my understanding an exemption is a an error that is expected and try catch is used to handle exemptions, so I'm confused if an exemption is an expected error how do you use try catch to handle unexpected exception, its seems like a contradiction. To reiterate the defining factor that seems to determine whether or not to use a try catch block vs an if else if is what I'm preceiving as a contradiction, so I don't understand when to use one. I'm looking for a high level description on when to use a try catch block. What am I missing?

2 Answers

Since this can be a highly debatable subject, I will tell you what I do personally.

I usually use try/catch blocks when I am dealing with certain technologies - for example input/output of data objects or streams of data. I also will use it a little more in initial pilot development and then remove them after regression testing. There are times when some things really just are unpredictable and you want your application to make sure the user is notified and your program crashes gracefully. Another thing to think about is that it is generally preferred to do checks for code that can CAUSE an exception (null values, empty objects, etc.) before executing code (thus eliminating the need for try/catch). Something like (pseudo code):

if (myObj == null) { // fail and let user know }
if (myObj.Name === "") { // fail and let user know }

However sometimes there are simply too many possible exceptions available that you check for the most common and catch the rest. So something like (pseudo code):

try
{
    //do something that might cause an exception
}
catch (NullValueException){}
catch (InvalidArgumentException){}
catch (CustomException){}
catch {}

The reason this topic is generally confusing for newer programmers is because you get a lot of opinions and talk about compute cost, nesting headaches, bubbling, etc. All of that is valid and important - but don't let it overwhelm you. Most tasks/routines you write in your software will not need a try/catch block. If you are worried the method you are coding is getting too complex to check for all possibilities, try wrapping some of the code that has the possibility to generate an exception in known exception types and start that way. Don't worry about compute costs in initial development as you can shave off cpu cycles later on.

I will say you should stay away from the general catch - one catch for all exceptions. This is generally bad practice and not recommended...well...ever. One reason being it provides NO HELP to you or anyone who may be possibly using your framework, library, objects, etc. I can't say you will always be able to find a way to get around the general catch, but I'd try really hard before doing it.

// BAD CODE
try
{
    // do something that might cause an exception
}
catch {}

Not sure if that really helped you out, but I get your concern. I'd say don't invest too heavily in the "right" way to do it - start feeling out your code and adapt. If you are getting unhandled exceptions during development phases, throw a try/catch in there and start catching those exceptions until you've hammered out what is causing the problems. Good luck!

Thanks for this comment. Learning try/catch without fully understanding why or when to use it was frustrating. Your comment helped me understand how I should take it as a tool.

Steven Parker
Steven Parker
242,296 Points

These points may help clear things up:

  • you may be confusing the term "exception" with "exemption".
  • an exception is only expected if it is generated by your own program
  • exceptions can also be generated by the system, and those might be prepared for even if not expected

A reason you might use an exception instead of a direct test could be that the place you wish to test for some condition might be in a different scope, such as inside a function you are calling. The function can cause an exception which the caller can catch, even if the caller did not have access to the values needed to determine the condition itself.