Error objects are created by using one of these built-in constructors:
- EvalError
- RangeError
- ReferenceError
- SyntaxError
- TypeError
- URIError
All of these constructors inherit from the Error object.
An example of an error will be trying to call a function that doesn't exist
>>> iDontExist();
try {
iDontExist();
} catch (e) {
// do nothing
}
try {
iDontExist();
} catch (e) {
alert(e.name + ': ' + e.message);
} finally {
alert('Finally!');
}
You can also create error objects yourself using new Error() or any of the other error constructors
try {
var total = maybeExists();
if (total === 0) {
throw new Error('Division by zero!');
} else {
alert(50 / total);
}
} catch (e) {
alert(e.name + ': ' + e.message);
} finally {
alert('Finally!');
}
Alternatively, you don't need any constructor; you can simply throw a normal object:
throw {
name : "MyError",
message : "OMG! Something terrible has happened"
}
No comments:
Post a Comment