DEV Community

Discussion on: Try-Catch vs if-else

Collapse
 
ahferroin7 profile image
Austin S. Hemmelgarn

First off, your statement is only accurate if you're dealing with manually generated errors/exceptions. Not all errors or exceptions are going to be something your code produces, some come from the JavaScript engine itself (or whatever libraries you are using.

Otherwise though, scoping is the big advantage of try-catch over if-else. More specifically, you can do stuff like this:

try {
    function1()
    function2()
    function3()
} catch (error) {
    // This code will get run if any of the above functions throws an error
}

With if-else, you have to explicitly check the return value of each function.

A better analogy than if-else would be that it's a special syntax for a scoped handler for the error event. In effect, the contents of the catch block are equivalent to a single-argument function that runs as the handler for the error event, but only if the error comes from inside the try block. This is, in a way, similar to the cooncept of using POSIX singals to inform C (or C++, or whatever other language) programs about specific hardware or OS errors (see SIGFPE and SIGBUS for very specific examples).

That said, I'd argue that JavaScript suffers from a questionable try-catch-finally design. The requirement to bind the exception to a variable and then inspect that in the catch handler to figure out what type of error even happened requires that you explicitly propagate any errors you don't handle, which in turn makes it easy to accidentally 'lose' errors that should indeed propagate.