Errors can happen and in JavaScript, they do happen most of the time! There are multiple causes that show this annoying red message:
- Syntax error: we can spend time reviewing our code and we never realized that there was a missing semicolon or brackets.
- Range error: this error is out of range or undefined. It can be an invalid date or an invalid array length.
- Reference error: this error occurs when we assign a value to a variable that doesn't exist. It could be an undefined x or assignment to an undeclared variable x.
- Type error: there's an error when the value is unexpected type.
Note: There are some JavaScript Exception solvers we can use as well if we prefer.
And so on. We will see this later.
So, when that happens, the code doesn't run and it's stuck. How can we fix these errors? With this!
Try... Catch can save the code
When an error occurs, the JavaScript code stops running and shows an error message.Ā Try... catchĀ is a block of code and it will be the solution.
We useĀ tryĀ when testing a block of code to see if there is an error during its execution. Then, theĀ catchĀ statement will be executed in case there is an error. TheĀ errĀ fromĀ *catch(err)Ā *--- can be named as you preferred - defines an error object and provide details of how to handle this error. When the catch registers an error, we will use console.error() instead of console.log(). This is the correct way in order to report an error and add it to the error list which occurs on the page.
When there is an error, JavaScript stops running and it throws an exception or error. The error object can have two properties:
-
Error name can return different values:
-
Eval Error has occurred in the eval() function. However, new Javascript versions don't use this error. Instead, we can use SyntaxError.
-
Range Error: when there a number out of range.
-
Reference Error: when a variable is not declared.
-
Syntax Error: when a syntax error occurs. It's so typical to miss a semicolon for example.
-
Type Error: when a value is out of range because of the type of variable. For example, a number can't be uppercase.
-
URI Error: when there's an error in
encodeURI()
- Uniform Resource Identifier. URI is a sequence of characters which identifies the resources used by web technologies. -
An error message provides information about the error.
If the error object is not needed, we can useĀ catch{}
Ā instead ofĀ catch(err){}
.
If we want that try... catch works, you must ensure the code is valid and runnable - no syntax error such as unmatched curly braces. Once it's readable, the engine reads and runs the code. Then, it will execute theĀ try... catchĀ when it can't understand this code.
Try... Catch structure
This is an example of how we can use try...catch
. This example calls a function which returns an
array of months depending on the function's previous value. If the value is not a month number
between 1 and 12, it will throw an exception called InvalidMonthNo
and the catch block will
convert the variable monthName
to unknown
.
Example from developer.mozilla.org
Oh, wait! What doesĀ throw - new Error ---Ā means?
Try... Catch with throw an error structure
Well, as we have seen before, when there is an error in the code, the code stops running. When using the throw statement, we can control the flow and customize our own error and the error message by throwing an error or an exception. You can customize it as a string, object, boolean, or as a number.
Finally, the final statement
We executeĀ finallyĀ despite theĀ try... catch. This block is always executed after try... catch. This block will be executed either way: if there is or not an exception. Finally always makes sure that the code will be executed, even if there is an error.
Try... Catch... Finally structure
If finally returns a value, this value will be the return value in the whole Try... Catch... FinallyĀ block, and it doesn't matter what's the return value in theĀ Try... CatchĀ block.
Example for Try... Catch... Finally
Nested Try... Catch blocks
It's possible to nested Try... Catch. IfĀ tryĀ doesn't have its ownĀ *catchĀ *it must have a finally block and the catch block attached to the try... catch is tested in order make a coincidence. Here's an example of the structure and how it works.
The exception will be captured by the closest catch. Any new exception in the internal block will be captured by the external block.
Conclusion
The Try... CatchĀ block handles runtime errors. It means that if you try to run the first block of code, the second block catches the errors which occur in it.
Error object has these two properties:
- Name
- Message
We can use catch{}
if an error object is not needed.
Using throw ---an error object, we can generate our own exceptions.
If using finally, the return value of this block is only valid.