迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

在 JavaScript 中使用不带 Catch 的 try 语句

作者:迹忆客 最近更新:2024/03/19 浏览次数:

今天的文章将介绍在 JavaScript 中不实现 catchtry 语句。


在 JavaScript 中实现没有 CatchTry

JavaScript try 块用于封装可能引发异常的代码。它必须在方法中使用。

如果特定语句中发生异常,则应在 catch 语句中捕获。

语法:

try {
  try_statements
  /* Code to executed */
} catch (exception_var) {
  catch_statements
  /* Handle exception */
} finally {
  finally_statements
  /* Final Code/Clean variables */
}

try 语句由包含一个或多个语句的 try 块组成。 {} 应始终使用,即使对于单个语句也是如此。

必须存在 catch 块或 finally 块。这为我们提供了 try 语句的三种组合。

  1. try...catch
  2. try...finally
  3. try...catch...finally

catch 块包括指定在 try 块中抛出异常时要同时做什么的语句。如果 try 块中的语句(或从 try 块调用的函数中)抛出异常,控制立即切换到 catch 块。

如果在 try 块中没有抛出异常,catch 块将被忽略/跳过。

finally 块总是在 trycatch 块完成执行后执行。无论异常是被抛出还是被卡住,finally 块通常与它内部的语句一起执行。

可以嵌套一个或多个测试语句。如果内部 try 语句没有处理错误的 catch 块,则使用封闭 try 语句的 catch 块代替。

try 语句也可用于处理 JavaScript 异常。如果抛出异常,则 finally 块中的语句最终将执行,即使没有 catch 块处理异常。

你可以在 try...catch 的文档中获得有关 try...catch 的更多信息。

让我们通过下面的例子来理解它。

try {
  console.log('Executing try block')
  throw new Error(0 / 0)
} finally {
  console.log('Final Call')
}

在上面的例子中,我们定义了一个没有 catchtry。我们通过将 0 除以 0 来抛出错误。

它将抛出一个 NaN 错误,由于缺少 catch 块,finally 块不会捕获该错误,并在 finally 块中打印 "Final Call" 语句。你还可以使用这些块来执行所需的操作并清理 finally 块中未使用的变量/资源。

尝试在任何支持 JavaScript 的浏览器中运行上述代码片段;它将在下面显示结果。

Executing try block
Final Call

演示

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便