Skip to main content

Try-Catch-Finally Blocks

In TypeScript, you will inevitably encounter errors. These errors may be due to unexpected user input, inadequate system resources, or bugs. When errors occur, it's important to handle them appropriately to prevent a program from crashing or behaving unexpectedly. One of the primary ways to handle errors in TypeScript is through the use of Try-Catch-Finally blocks.

The Try Block

The try block houses the code segment that could potentially throw an error. It sets up a testing ground for your code. The code inside a try block is executed line by line. If an error occurs, the execution of the try block is stopped, and control is passed to the catch block.

Here's a basic example of a try block:

try {
let x = y; // ReferenceError: y is not defined
}

In this example, an error will be thrown because y is not defined.

The Catch Block

The catch block is used to catch and handle the error thrown from the try block. The catch block receives the error object that contains information about the error.

Here's how you add a catch block to our previous example:

try {
let x = y; // ReferenceError: y is not defined
}
catch(error) {
console.log(error.message); // logs "y is not defined"
}

In this example, the catch block catches the error thrown from the try block and logs the error message to the console.

The Finally Block

The finally block contains code that will be executed regardless of whether an error was thrown or caught. This block is optional and is often used for cleaning up code, such as closing files or clearing resources, whether an error has occurred or not.

Here's how you add a finally block to our previous example:

try {
let x = y; // ReferenceError: y is not defined
}
catch(error) {
console.log(error.message); // logs "y is not defined"
}
finally {
console.log('This will run regardless of an error occurring or not');
}

In this example, the message in the finally block will be logged regardless of whether an error occurred in the try block.

Advanced Error Handling

If your application has specific types of errors that need to be handled differently, you can throw your own errors using the throw keyword and catch them in the catch block.

Here's an example:

try {
throw new Error('This is a custom error');
}
catch(error) {
console.log(error.message); // logs "This is a custom error"
}

In this example, a new error is created and thrown from the try block. The catch block then catches this error and logs the error message to the console.

In conclusion, try-catch-finally blocks offer a powerful way to handle errors in TypeScript. By using these blocks, you can ensure that your program handles errors gracefully and continues to function correctly under various circumstances.