JavaScript Error Handling
Exceptions can be used to jump out of the current code block, specifying a type of error, which can then be properly dealt with in the code outside of the block.
Throwing exceptions
function myFunction () {
// Your code here
if ( /* Your condition here */ ) {
throw new Error ("Your error text");
}
}
- To be more specific, you can replace Error with other kinds of errors such as SyntaxError, TypeError, ...
Try-catch blocks
function myFunction () {
try {
// Code that might fail (throw errors)
}
catch (myError) {
// Code to respond if it fails
}
}
- Use this when calling functions that may throw an exception.
Throwing and catching different kinds of exceptions
function myFunction () {
try {
// Code that might fail (throw exceptions)
}
catch (myError) {
if (myError instanceof TypeError) {
// Code to respond if it fails
}
else if (myError instanceof RangeError) {
// Code to respond if it fails
}
else {
// Code to respond if it fails
}
}
}
- Use this to react differently to different errors.
Showing a stack trace
catch (myError) {
console.error(myError.stack);
}
- Use this to have the program display (in the console) the line of the error, and sequence of calls that lead to it.
Challenge
Write a function that accepts a parameter called nameParam, have it call the function nameParam.charAt(0) to get the first letter of the name. If there is a TypeError, have it display "The nameParam parameter must be a string". If it has some other kind of error, have it display "Something went wrong". Either way, have it display the stack trace to the console. Test it by calling your function with a number (rather than text) as the passed parameter.
Completed