Multiple catch in javascript

后端 未结 4 961
清歌不尽
清歌不尽 2021-01-04 00:34

Is it possible to use multiple catch in JS(ES5 or ES6) like I describe below (it is only example):

try {
­­­­  // just an error
  throw 1; 
}
ca         


        
相关标签:
4条回答
  • 2021-01-04 01:21

    This Kind of Multiple Catch we call in javascript as Conditional catch clauses

    You can also use one or more conditional catch clauses to handle specific exceptions. In this case, the appropriate catch clause is entered when the specified exception is thrown. As below

    try {
        myroutine(); // may throw three types of exceptions
    } catch (e if e instanceof TypeError) {
        // statements to handle TypeError exceptions
    } catch (e if e instanceof RangeError) {
        // statements to handle RangeError exceptions
    } catch (e if e instanceof EvalError) {
        // statements to handle EvalError exceptions
    } catch (e) {
        // statements to handle any unspecified exceptions
        logMyErrors(e); // pass exception object to error handler
    }
    

    Non-standard: But This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

    Reference

    0 讨论(0)
  • 2021-01-04 01:25

    Try in a that way:

    try {
      throw 1; 
    }
    catch(e) {
        if (e instanceof ReferenceError) {
           // ReferenceError action here
        } else if (typeof e === "string") {
           // error as a string action here
        } else {
           // General error here
        }
    }
    finally {}
    
    0 讨论(0)
  • 2021-01-04 01:27

    There is absolutely nothing wrong with multiple if/then/else of course, but I never liked the look of it. I find that my eyes skim a bit faster with everything lined up, so I use the switch approach instead to help me skim/seek to the correct block. I've also started using a lexical scope {} to enclose case blocks now that the ES6 let command has gained popularity.

    try {
    
      // OOPS!
    
    } catch (error) {
    
      switch (true) {
        case (error instanceof ForbiddenError): {
          // be mean and gruff; 
          break;
        }
        case (error instanceof UserError): {
          // be nice; 
          break;
        }
        default: {
          // log, cuz this is weird;
        }
      }
    
    }
    
    0 讨论(0)
  • 2021-01-04 01:34

    No. That does not exist in JavaScript or EcmaScript.

    You can accomplish the same thing with an if[...else if]...else inside of the catch.

    There are some non-standard implementations (and are not on any standard track) that do have it according to MDN.

    0 讨论(0)
提交回复
热议问题