Error Handling
In programming errors happen for various reasons, some happen from code errors, some due to wrong input, and other unforeseeable things. When an error happens, the code stops and generates an error message usually seen in the console.
Instead of halting the code execution, we can use the try...catch
construct that allows catching errors without dying the script. The try...catch
construct has two main blocks; try
and then catch
.
At first, the code in the try
block is executed. If no errors are encountered then it skips the catch
block. If an error occurs then the try
execution is stopped, moving the control sequence to the catch
block. The cause of the error is captured in err
variable.
try...catch
works for runtime errors meaning that the code must be runnable and synchronous.
To throw a custom error, a throw
statement can be used. The error object, that gets generated by errors has two main properties.
name: error name
message: details about the error
Last updated
Was this helpful?