When should you use try/catch in JavaScript?

后端 未结 7 921
旧时难觅i
旧时难觅i 2021-01-30 00:53

When I\'m developing normal web application with JavaScript, the try/catch statement is not needed usually. There\'s no checked exception, File IO or database conne

相关标签:
7条回答
  • 2021-01-30 01:29

    One scenario I find try/catch/finally useful is with deeply nested objects where a null can pop up at any level. for example, consider this:

    var something = one.two.three.four.five;
    

    to perform this "get" with 100% safety one would have to write a bit of verbose code:

    if(one && one.two && one.two.three && one.two.three.four)
       something = one.two.three.four.five;
    

    Now imagine the variable names are realistic and longer and you quickly get a very ugly code if statement.

    I tend to use try/catch/finally to simplify this when I don't care about any "else" scenarios and just want the object or not:

    var something;
    try { something = one.two.three.four.five; }
    catch { something = "default"; }
    finally { doSomething(something); }
    
    0 讨论(0)
  • 2021-01-30 01:33

    I don't agree this is a good scenario to use try...catch in JavaScript:

    var something;
    try { something = one.two.three.four.five; }
    catch { something = "default"; }
    finally { doSomething(something); }
    

    https://stackoverflow.com/a/26172702/12410906

    Because Remembering To Condition If Object Exist Before Reading Its Prop is something that belongs to JavaScript knowledge. You can't pretend you don't know it and just write a deep prop reading chain and wrap a try...catch around it. It is like if you call a primitive value like a function will also trigger exception:

    const val = 1
    val()
    

    You can't pretend you don't know it and wrap a try...catch around every call of function. I do agree that it is very easy to forget condition if object exists when reading prop in JavaScript, but that is because javascript's design fault (typescript solve this issue with optional chaining operator), in one word that's not a good example to show when to use try...catch.

    To understand when to use try...catch needs to understand when to throw error first.

    When to throw error

    An Error Is Something Thrown By Producer To Consumer When Something Really Bad Happens That Makes The Producer Has To Stop Until The Consumer (in most cases) Make Change.

    For example, if backend API is producer, frontend code would-be consumer. When frontend requests something that backend doesn't have, backend can't continue so it throws a 404 error to frontend; when frontend requests something that being protected without validation, the backend would throw a 401 error to force the frontend input username and password; when there's server hard drive explodes, there will be another form of error thrown(if the server can still run).

    Frontend code can also be frontend code's consumer. For example, you are using jQuery library, jQuery would-be producer, and your frontend code would-be consumer. This is an example in source code of jQuery throwing an error:

    // from jQuery source code
            function( w ) {
                if ( !w.document ) {
                    throw new Error( "jQuery requires a window with a document" );
                }
                return factory( w );
            };
    

    See, the frontend developer(consumer) use jQuery in an environment that even document does not exist, so jQuery(producer) really can't go on and throw an error and stop everything until the developer do it right.

    If you are developing a web app, the uesr who browser your web app would be consumer, then your web app code would be producer. There will be shit things happen surely, like the user might request a url does not exist(assume in spa app), or the user might input english letters in mobile number input, if you just simply throw an error like jQuery, Vue, backend would do, the user(consumer) can't catch it and consume it.

    What you would really do is to show some toast or navigate to a special 404 route to let the user know what happens. That's why most of us frontend developers seldomly throw an error.

    When to try...catch

    This question will be easy after understanding when to throw an error. If you are consuming a producer that might throw error, you try...catch it, this is a piece of source code from vue-next:

    // from vue-next source code
    
     try {
        result = postcss(plugins).process(source, postCSSOptions)
        ...
       }catch(e){}
    

    The reason it try...catch is because the plugin postcss will throw error when the input is not right. Or you try to JSON.parse a string from server, you try...catch it. That's a general principle.

    0 讨论(0)
  • 2021-01-30 01:39

    Well, I personally (mis?)use it, when I write some code which I'm not sure will execute properly, but the user don't need to know about the error.

    Other than that, I've been using it on some user controls, to which you can define an 'action' property in your HTML markup, and the javascript will try executing that action, like this:

    try{
         window['method'](args);
    }catch(e){
         try{
             window['optionalExceptionHandler'](e, args);
         }catch(e){ return; }
    }
    

    (I like to think it's better than eval() xD)

    0 讨论(0)
  • 2021-01-30 01:41

    I found this from a post here:

    When Should You Use try-catch?

    The try-catch statement should be used any time you want to hide errors from the user, or any time you want to produce custom errors for your users’ benefit. If you haven’t figured it out yet, when you execute a try-catch statement, the browser’s usual error handling mechanism will be disabled.

    You can probably see the possible benefits to this when building large applications. Debugging every possible circumstance in any application’s flow is often time consuming, and many possibilities could be inadvertantly overlooked. Of course, with proper bug testing, no area should be overlooked. But the try-catch statement works as a nice fallback in areas of your code that could fail under unusual circumstances that were not foreseen during development.

    Another benefit provided by the try-catch statement is that it hides overly-technical error messages from users who wouldn’t understand them anyhow.

    The best time to use try-catch is in portions of your code where you suspect errors will occur that are beyond your control, for whatever reasons.

    When Should try-catch be Avoided?

    You shouldn’t use the try-catch statement if you know an error is going to occur, because in this case you would want to debug the problem, not mask it. The try-catch statement should be executed only on sections of code where you suspect errors might occur, and due to the overwhelming number of possible circumstances, you cannot completely verify if an error will take place, or when it will do so. In the latter case, it would be appropriate to use try-catch.

    0 讨论(0)
  • 2021-01-30 01:44

    try...catch blocks are generally encourages to be used less, and this doesn't depend on the language you use.

    The main reason for this is the cost of catch blocks. Also another reason is that, when you wrap many statements with a single try...catch block, in catch block you can't be sure what was exactly the main problem.

    It's better to use techniques like input validation or if...else blocks to reduce the probability of an exception (error) to happen. For example, when you want to work with a number which is taken from user, instead of using try...catch, you can use:

    if (isNaN(numberVariable))
    {
        alert('you should enter a valid number');
    }
    
    0 讨论(0)
  • 2021-01-30 01:49

    External Javascript libraries and widgets often make use of exceptions for instantiation errors. It's common to need to:

    try {
      var w = new Widget();
    }
    catch (e) {
      // widget failed
    }
    
    0 讨论(0)
提交回复
热议问题