JavaScript try/catch/finally 关键字
最后修改于 2025 年 4 月 16 日
在本文中,我们将展示如何使用 JavaScript 中的 try/catch/finally
关键字处理错误。
try/catch/finally 关键字
try/catch/finally
语句标记一个要尝试执行的代码块,并指定在抛出异常时采取的响应。它允许优雅的错误处理,而不是突然的程序终止。
try
块包含可能抛出异常的代码。catch
块包含处理异常的代码。无论结果如何,finally
块都会在 try/catch 之后执行。
JavaScript 错误可以由运行时抛出,或使用 throw
语句显式抛出。try/catch/finally 结构提供了结构化的异常处理,类似于其他编程语言。
基本 try/catch 示例
以下示例演示了 try/catch 的基本用法。
try { let result = riskyOperation(); console.log(result); } catch (error) { console.log('An error occurred:', error.message); }
此代码尝试执行 riskyOperation()
,它可能会抛出错误。如果发生错误,执行将跳转到 catch 块。错误对象包含有关出错的详细信息。
$ node main.js An error occurred: riskyOperation is not defined
捕获特定错误类型
JavaScript 允许捕获特定错误类型以进行更精确的处理。
try { JSON.parse('invalid json'); } catch (error) { if (error instanceof SyntaxError) { console.log('Syntax error:', error.message); } else { console.log('Unexpected error:', error); } }
此示例专门检查解析 JSON 时的 SyntaxError
。可以以不同的方式处理不同的错误类型。 instanceof
运算符检查错误类型。
$ node main.js Syntax error: Unexpected token i in JSON at position 0
finally 块
无论是否发生错误,finally
块都会执行。
let connection = { open: true }; try { console.log('Using connection'); throw new Error('Network failure'); } catch (error) { console.log('Error:', error.message); } finally { connection.open = false; console.log('Connection closed'); }
在这里,finally
确保即使发生错误,连接也能正确关闭。这对于清理操作(例如关闭文件或数据库连接)很有用。
$ node main.js Using connection Error: Network failure Connection closed
嵌套 try/catch 块
try/catch 块可以嵌套以处理不同级别的错误。
try { try { nonExistentFunction(); } catch (innerError) { console.log('Inner catch:', innerError.message); throw new Error('Wrapped error'); } } catch (outerError) { console.log('Outer catch:', outerError.message); }
此示例显示了嵌套错误处理。内部 catch 处理初始错误,然后抛出一个由外部 catch 捕获的新错误。这允许错误包装和重新抛出。
$ node main.js Inner catch: nonExistentFunction is not defined Outer catch: Wrapped error
自定义错误抛出
您可以使用 throw
语句抛出自定义错误。
function validateAge(age) { if (age < 0) { throw new Error('Age cannot be negative'); } if (age > 120) { throw new RangeError('Age seems invalid'); } return age; } try { validateAge(150); } catch (error) { console.log(error.name + ':', error.message); }
此函数根据验证失败抛出不同的错误类型。自定义错误提供了关于发生错误的有意义的反馈。错误类型有助于对不同的失败情况进行分类。
$ node main.js RangeError: Age seems invalid
带有 try/catch 的 Async/await
try/catch 与 async 函数一起使用以处理 promise 拒绝。
async function fetchData() { try { let response = await fetch('https://invalid.url'); let data = await response.json(); console.log(data); } catch (error) { console.log('Fetch failed:', error.message); } } fetchData();
此示例显示了 async 代码中的错误处理。try/catch 块捕获网络错误和 JSON 解析错误。Async/await 使基于 promise 的错误处理更直观。
$ node main.js Fetch failed: fetch failed
错误对象属性
错误对象包含用于调试的有用属性。
try { null.someProperty; } catch (error) { console.log('Name:', error.name); console.log('Message:', error.message); console.log('Stack:', error.stack.split('\n')[0]); }
此代码演示了常见的错误属性。 name
标识错误类型。 message
提供人类可读的描述。 stack
包含用于调试的调用堆栈跟踪。
$ node main.js Name: TypeError Message: Cannot read properties of null (reading 'someProperty') Stack: TypeError: Cannot read properties of null (reading 'someProperty')
来源
在本文中,我们已经演示了如何使用 try/catch/finally 在 JavaScript 中进行错误处理。