JIYIK CN >

Current Location:Home > Learning > PROGRAM > TypeScript >

Handling exceptions with try..catch..finally in TypeScript

Author:JIYIK Last Updated:2025/04/15 Views:

This article will discuss try..catch..finallyhandling exceptions in TypeScript using the statement.

Handling exceptions in TypeScript

In TypeScript, try..catch..finallya block handles exceptions that occur during program runtime. It allows the program to run correctly and not end randomly.

The main code where an exception might occur is placed tryinside the block. If an exception occurs, it goes to the block that handles it catch; however, if no error is encountered, catchthe block is skipped.

In any case, finallythe block will always execute regardless of whether errors occur in the program.

try..catch..finallyBelow are some code examples that illustrate how we can use exception handling in TypeScript .

function doOrThrow<T>(error: T): true{
    if (Math.random() > .5){
        console.log('true')
        return true;
    }
	else{
        throw error;
    }
}
try{
    doOrThrow('err1');
    doOrThrow('err2');
    doOrThrow('err3');
} 
catch (e:any){
    console.log(e,'error')
}
finally{
    console.log("Terminated");
}

Output:

Use try-catch-finally to check if the number is greater than 5

tryThe function inside the block is called three times, and it is passed one argument. If the number generated is greater than 0.5, it executes ifthe block and returns true.

Otherwise, it will throw an error which catchis handled in the block. It tells which call it will throw after executing tryand .catch

Let’s consider another example.

let fun: number; // Notice use of `let` and explicit type annotation
const runTask=()=>Math.random();
try{
    fun = runTask();
    console.log('Try Block Executed');
    throw new Error("Done");
}
catch(e){
    console.log("Error",e);
}
finally{
    console.log("The Code is finished executing.");
}

Output:

Example of using try-catch-finally in TypeScript

unknownType catchclause variables

Prior to TypeScript's 4.0 版, catchclause variables were typed any. Since variables had the type assigned to them any, they lacked type safety, leading to invalid operations and errors.

Now, TypeScript's __INITIALIZE__ 4.0 版allows us to specify catchthe types of clause variables unknown, which is anymuch safer than __INITIALIZE__ .

It reminds us that we need to perform some kind of checking before operating on a value.

try {
    // ...
}
catch (err: unknown) {
    // error!
    // property 'toUpperCase' does not exist on 'unknown' type.
    console.log(err.toUpperCase());

    if (typeof err === "string") {
        // works!
        // We have narrowed 'err' down to the type 'string'.
        console.log(err.toUpperCase());
    }
}

Previous: None

Next: None

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

在 TypeScript 中返回一个 Promise

Publish Date:2023/03/19 Views:590 Category:TypeScript

本教程讨论如何在 TypeScript 中返回正确的 Promise。这将提供 TypeScript 中 Returns Promise 的完整编码示例,并完整演示每个步骤。

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial