How to Use Try Catch in TypeScript?

As a developer, you should know how to use try-catch blocks to handle unexpected errors and exceptions in any programming language. In this tutorial, I will explain how to use try-catch in TypeScript with examples. I will also explain how to use try...catch, try...finally, and try...catch...finally blocks in TypeScript.

Try-Catch in TypeScript

Error handling is an essential part of any robust application. In TypeScript, the try-catch block is used to handle exceptions that may occur during code execution. This mechanism allows developers to catch and handle errors appropriately rather than letting the application crash.

Syntax of try-catch

The basic syntax of a try-catch block in TypeScript is:

try {
    // Code that may throw an error
} catch (error) {
    // Code to handle the error
}

Syntax of try…finally

The try...finally statement includes a finally block that executes whether or not an exception is thrown in the try block. Here is the try…finally syntax:

try {
    // Code that may throw an error
} finally {
    // Code that will always execute
}

Syntax of try…catch…finally

Combining both catch and finally allows you to handle errors and execute cleanup code regardless of whether an error occurred.

Here is the syntax of try…catch…finally in TypeScript.

try {
    // Code that may throw an error
} catch (error) {
    // Code to handle the error
} finally {
    // Code that will always execute
}

Check out Differences Between TypeScript and JavaScript

TypeScript try-catch Examples

Now, let me show you some real examples of how to use TypeScript try catch block.

try…catch in TypeScript Example

The try...catch block is used to handle exceptions that may be thrown during the execution of a block of code. Let me give an example of how to use this.

function parseJSON(jsonString: string): any {
    try {
        return JSON.parse(jsonString);
    } catch (error) {
        console.error("Parsing error:", error);
        return null;
    }
}

const validJSON = '{"name": "John", "age": 30}';
const invalidJSON = '{"name": "John", "age": 30';

console.log(parseJSON(validJSON));  // Output: { name: 'John', age: 30 }
console.log(parseJSON(invalidJSON));  // Output: Parsing error: SyntaxError: Unexpected end of JSON input
                                      //         null

In this example, the parseJSON function attempts to parse a JSON string. If the string is invalid, the catch block catches the SyntaxError and logs it, returning null instead.

Here is the exact output in the screenshot below:

Try Catch in TypeScript

try…finally in TypeScript Example

The finally block is useful for executing code that should run regardless of whether an error occurred. This is often used for cleanup tasks.

function readFile(filePath: string): void {
    let fileHandle: any;
    try {
        fileHandle = openFile(filePath);  // Hypothetical function
        // Perform operations on the file
    } finally {
        if (fileHandle) {
            closeFile(fileHandle);  // Hypothetical function
        }
    }
}

readFile("example.txt");

In this example, closeFile is called regardless of whether an error occurs in the try block, ensuring that the file handle is properly closed.

Check out How to Check TypeScript Version?

try…catch…finally in TypeScript Example

Combining try, catch, and finally blocks allows for comprehensive error handling and cleanup.

Here is an example.

function processString(input: string | null): string {
    let processedString: string = "";

    try {
        if (input === null) {
            throw new Error("Input string cannot be null");
        }
        // Simulate string processing
        processedString = input.trim().toUpperCase();
        console.log("Processed string:", processedString);
    } catch (error) {
        console.error("Error processing string:", error);
    } finally {
        console.log("String processing complete");
    }

    return processedString;
}
const inputString1 = "  Hello, TypeScript!  ";
const inputString2 = null;
console.log("Result for inputString1:", processString(inputString1));
console.log("Result for inputString2:", processString(inputString2));
  • Input Validation: The function checks if the input string is null. If it is, it throws an error.
  • String Processing: If the input is valid, the function trims the whitespace from the input string and converts it to uppercase.
  • Error Handling: If an error occurs (e.g., the input is null), it is caught in the catch block, and an error message is logged.
  • Finally Block: The finally block logs a message indicating that the string processing is complete, regardless of whether an error occurred.

Here is the exact output after I executed the above program using the below commands.

tsc TypescriptExamples.ts
node TypescriptExamples.js

You can also see the screenshot below:

typescript try catch

Check out Is TypeScript Frontend or Backend?

try…catch…throw in TypeScript

You can also rethrow exceptions from the catch block if you want the error to be handled further up the call stack.

Here is how to use try…catch…throw in TypeScript.

function validateAge(age: number): void {
    if (age < 0 || age > 150) {
        throw new Error("Invalid age provided");
    }
}

function registerUser(age: number): void {
    try {
        validateAge(age);
        console.log("User registered successfully");
    } catch (error) {
        console.error("Registration error:", error);
        throw error;  // Rethrow the error
    }
}

try {
    registerUser(-5);
} catch (error) {
    console.error("Caught in main:", error);
}

In this example, the registerUser function rethrows the error after logging it, allowing the main code block to catch and handle it further.

Check out How to Handle Catch Error Types in TypeScript?

The Finally Block in TypeScript

The finally block in TypeScript is particularly useful for cleanup tasks, regardless of whether an error occurred. This can include closing files, releasing resources, or resetting states.

Here is an example to help you understand how to use the finally blocks in TypeScript.

function performTask(): void {
    try {
        console.log("Task started");
        // Simulate a task that may throw an error
        throw new Error("Something went wrong");
    } catch (error) {
        console.error("Error during task:", error);
    } finally {
        console.log("Task completed");
    }
}

performTask();

In this example, the message “Task completed” is logged regardless of whether an error occurs, ensuring that the task’s completion is always acknowledged.

You can also see the exact output in the screenshot below:

Finally Block in TypeScript

Conclusion

Error handling in TypeScript is enhanced by its strong typing system, allowing for more predictable and manageable code. The try...catch, try...finally, and try...catch...finally blocks helps to handle errors in TypeScript. I hope you now understand how to use Try Catch in TypeScript from the above examples.

You may also like: