JavaScriptでエラーを作成するには、 、特定のタイプのError、または任意のObjectまたはStringにする必要があります。throw
Error
function five_is_bad(x) {
if (x===5) {
// `x` should never be 5! Throw an error!
throw new RangeError('Input was 5!');
}
return x;
}
console.log('a');
try {
console.log('b');
five_is_bad(5); // error thrown in this function so this
// line causes entry into catch
console.log('c'); // this line doesn't execute if exception in `five_is_bad`
} catch (ex) {
// this only happens if there was an exception in the `try`
console.log('in catch with', ex, '[' + ex.message + ']');
} finally {
// this happens either way
console.log('d');
}
console.log('e');
/*
a
b
in catch with RangeError {} [Input was 5!]
d
e
*/