55

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; 
}
catch(e if e instanceof ReferenceError) {
­­­­  // here i would like to manage errors which is 'undefined' type
}
catch(e if typeof e === "string") {
  ­­­­// here i can manage all string exeptions
}
// and so on and so on
catch(e) {
  ­­­­// and finally here i can manage another exeptions
}
finally {
­­­­  // and a simple finally block
}

This is the same as we have in C# or in a Java.

2
  • 1
    One catch block and then check the type of the exception? Commented Nov 18, 2015 at 13:53
  • @Icepickle yeap you are right Commented Nov 18, 2015 at 13:54

5 Answers 5

39

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I see, just using the one catch block and then i can check exception with an exception type. Thanks!
Not exactly the same when you re-throw the error inside the catch block: for example node shows the line of the re-thrawn error, not the source line inside the try block (even if captureStackTrace handles it right). I think multiple catch conditional blocks would eliminate this problem altogether because you don't enter into the catch block if you will.
37

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 {}

Comments

9

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;
    }
  }

}

Comments

1

You can strongly type Error type as well based on error name.

Something like this...

try{
    await fetchNumber();
}catch(error){
    switch(error.name){
        case NoSuchElementError:{
            performIfNoSuchElementError();
            break;          
        }
        case NoClassDefFoundError:{
            performIfNoClassDefFoundError();
            break;          
        }
        //...
        default:{
            break;
        }   
    }
}

2 Comments

Welcome to Stackoverflow. This question is asked more than 7 years ago and it has an accepted answer. Please add some details about the reason you are adding a new answer.
@MDZand this is one of the first results when googling. It doesn't matter how old the question is; adding a newer answer ensures th questions answers are relevant still; otherwise i would come here, see the date and say "oh this is old its probably not applicable anymore" and keep searching, which is not useful. Thanks for trying to be constructive!
-2

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

1 Comment

Thanks, this is Non-standard JS that's why i couldn't find anything with it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.