// built-in constructors for standard errors let error = newError(message); let error = newSyntaxError(message); let error = newReferenceError(message); // ...
syntax
1 2 3 4 5 6 7 8 9 10
let json = '{ "age": 30 }'; // incomplete data
try { let user = JSON.parse(json); // <-- no errors if (!user.name) { thrownewSyntaxError("Incomplete data: no name"); // (*) } } catch(e) { alert( "JSON Error: " + e.message ); // JSON Error: Incomplete data: no name }
Rethrowing
catch should only process errors that it knows and “rethrow” all others (use instanceof)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
let json = '{ "age": 30 }'; // incomplete data
try { let user = JSON.parse(json); if (!user.name) { thrownewSyntaxError("Incomplete data: no name"); } blabla(); // unexpected error } catch(e) { if (e instanceofSyntaxError) { alert( "JSON Error: " + e.message ); } else { throw e; // rethrow (*) } }
try...catch...finally
finally is executed even with an explicit return.
finally is executed just before returns to the outer code.