Multiple catch in javascript

Is it possible to use multiple catch in J S(ES5 or ES6) as described below (this is just an 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 in C# or in Java .

Thanks in advance!

+5
source share
3 answers

No. It does not exist in JavaScript or EcmaScript.

You can do the same with if[...else if]...else inside catch .

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

+4
source

Try as follows:

 try { throw 1; } catch(e) { if (e instanceof ReferenceError) { } else if (typeof e === "string") { } else { } } finally { } 
0
source

We call this kind of multiple catch in javascript as conditional catch locks.

You can also use one or more conditional calculations to handle certain exceptions. In this case, the corresponding catch clause is introduced 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 function is non-standard and does not correspond to standard tracks. Do not use it on production sites facing the Internet: it will not work for each user. There may also be large incompatibilities between implementations, and behavior may change in the future.

Link

0
source

Source: https://habr.com/ru/post/1236230/


All Articles