MST

星途 面试题库

面试题:TypeScript 中处理错误的常见方式

请描述在 TypeScript 中至少两种处理错误的常见方式,并举例说明如何使用 `try...catch` 块来捕获和处理运行时错误,同时阐述类型系统在错误处理过程中起到的作用。
20.7万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

1. 处理错误的常见方式

使用 try...catch

在 TypeScript 中,try...catch 块用于捕获和处理运行时错误。例如:

try {
    let result = 10 / 0; // 这会抛出一个运行时错误
    console.log(result);
} catch (error) {
    console.log('捕获到错误:', error);
}

在上述代码中,try 块内的代码如果抛出错误,就会被 catch 块捕获,然后执行 catch 块内的逻辑来处理错误。

使用 if 条件判断

对于一些可以提前预知的可能导致错误的情况,可以使用 if 条件判断来避免错误发生。例如:

function divide(a: number, b: number): number | string {
    if (b === 0) {
        return '不能除以零';
    }
    return a / b;
}

let result = divide(10, 0);
if (typeof result ==='string') {
    console.log(result);
} else {
    console.log('结果:', result);
}

这里通过 if 判断除数是否为零,避免了运行时除以零的错误。

2. try...catch 块捕获和处理运行时错误示例

function readFileContents(filePath: string): string {
    // 模拟读取文件,这里简单抛出错误
    throw new Error('文件不存在');
}

try {
    let contents = readFileContents('nonexistent.txt');
    console.log(contents);
} catch (error) {
    if (error instanceof Error) {
        console.log('文件读取错误:', error.message);
    }
}

在这个例子中,readFileContents 函数模拟了读取文件的操作并抛出一个错误。try 块调用这个函数,catch 块捕获到错误后,通过 instanceof 判断错误类型,并打印错误信息。

3. 类型系统在错误处理过程中的作用

  • 提前发现错误:TypeScript 的类型系统可以在编译阶段发现许多潜在错误,例如类型不匹配等问题。这有助于在代码运行之前就捕获错误,减少运行时错误的发生。比如:
let num: number = '123'; // 编译错误,类型不匹配
  • 明确错误类型:在 catch 块中,通过类型系统可以更准确地判断错误类型,从而进行针对性的处理。如上面 try...catch 示例中,通过 instanceof 判断错误是否为 Error 类型,进而处理相关错误信息。这使得错误处理逻辑更加健壮和可靠。