1. The try...catch Statement
When a try block error occurs, control is passed to the catch block, which runs the appropriate error-handling code. The catch block receives the error object as a parameter, which gives the code access to the error's details.
The try...catch statement is helpful for addressing unforeseen problems that may happen while a program is being executed. You can catch problems and save the application from crashing by enclosing potentially troublesome code in a try block.
2. The try...catch...finally Statement
The catch block contains code that is executed when an error occurs in the try block. It takes an argument that represents the error object, which contains information about the error that occurred. The finally block contains code that is executed after the try and catch blocks, regardless of whether an error occurred. This block is useful for releasing resources, closing files, or cleaning up code after a block of code has executed.
The try block contains code that might throw an error. If an error occurs, control is transferred to the catch block, which will execute the code that handles the error. The finally block will then execute, regardless of whether an error occurred or not. The try...catch...finally statement is useful for handling errors and ensuring that code is executed regardless of whether an error occurred or not.
3. Throwing Errors
Throwing errors is useful when you want to create custom error messages or to control the flow of your code based on specific conditions. By throwing errors, you can prevent unexpected behaviour and ensure that your code runs smoothly and efficiently.
The Error object is the base type of all errors and it has two main properties a name property that specifies the type of error, and a message property that holds a message describing the error in more detail. Any error thrown will be an instance of the Error object.
The following section describes each one of these error type in more detail:
This error occurs when you try to use a value that is outside of the range of acceptable values. For example, if you try to create an array with a negative length.
This error occurs when you try to reference a variable or function that doesn't exist. For example, if you try to use a variable that hasn't been declared.
This error occurs when you try to perform an operation on a value that is of the wrong type. For example, if you try to add a string to a number.
URIError is a type of error that occurs when a global function that expects a valid Uniform Resource Identifier (URI) is passed an invalid URI.
The specific error type can also be thrown manually using their respective constructor and the throw statement, e.g., to throw a TypeError you can use the TypeError() constructor.