惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

GbyAI
GbyAI
J
Java Code Geeks
雷峰网
雷峰网
WordPress大学
WordPress大学
宝玉的分享
宝玉的分享
云风的 BLOG
云风的 BLOG
V
Visual Studio Blog
V
Vulnerabilities – Threatpost
S
Securelist
The Hacker News
The Hacker News
The Register - Security
The Register - Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Help Net Security
Help Net Security
G
Google Developers Blog
Hugging Face - Blog
Hugging Face - Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
M
MIT News - Artificial intelligence
AI
AI
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
The GitHub Blog
The GitHub Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Schneier on Security
Schneier on Security
N
Netflix TechBlog - Medium
T
The Blog of Author Tim Ferriss
Google DeepMind News
Google DeepMind News
Hacker News - Newest:
Hacker News - Newest: "LLM"
H
Hacker News: Front Page
博客园 - 司徒正美
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
B
Blog
Microsoft Azure Blog
Microsoft Azure Blog
大猫的无限游戏
大猫的无限游戏
Security Latest
Security Latest
Engineering at Meta
Engineering at Meta
N
News and Events Feed by Topic
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
酷 壳 – CoolShell
酷 壳 – CoolShell
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
T
Threat Research - Cisco Blogs
U
Unit 42
V
V2EX
V2EX - 技术
V2EX - 技术
L
LINUX DO - 最新话题
aimingoo的专栏
aimingoo的专栏
Microsoft Security Blog
Microsoft Security Blog
Recorded Future
Recorded Future
P
Privacy & Cybersecurity Law Blog
美团技术团队
小众软件
小众软件
F
Fortinet All Blogs

博客园 - 木乃伊人

VS Code 搭建LangChain开发环境 VSCode Unable to import XXX 问题解决记录 大模型应用开发-聊天机器人-保存聊天记录 TDD Google Chrome 默认非安全端口列表 EF Core的预先加载、延迟加载、实体追踪 同步、异步、回调 软件设计原则 UML类图 Seq Serilog 多线程整理 Vuex和Pinia Vue3+TS+Vite+pinia 枚举 Vite创建Vue3项目 闭包 IdentitySrever4 ElasticSearch 前端防止重复提交案例
try-catch中的throw和throw ex的区别
木乃伊人 · 2025-10-14 · via 博客园 - 木乃伊人

一、简介

       try-catch中的throw和throw ex是2种常见的用于抛出异常的方式,看似相似,但是它们的行为和影响有很大区别。

二、对比

  • throw:直接抛出当前的异常对象。
  • throw ex:重新抛出捕获到的异常对象。

三、分析

       【throw】

         最常用的抛出异常的行为。他会重新抛出当前捕获的异常对象,并保留原始异常信息,包括堆栈跟踪(Stack Trace),以为这你可以追溯到异常发生的最初始为止。

image

【throw ex】

          只能捕获到异常对象,但会重置异常堆栈信息,导致丢失原始异常的初始位置,而不是保留原始异常堆栈信息,进而导致调试和追踪异常变得困难,所以不推荐使用

image

四、推荐

       可以用 throw new Exception() 通过对异常的重新包装,且保留原始异常点信息。 推荐使用。      

image

 五、扩展

       5.1、多个try catch 嵌套,异常是如何捕获的?            

image

             【分析】:在一个函数中,当多个try-catch嵌套时,只会将最后一个异常抛出的位置记录到异常堆栈中。即ex3的位置,这叫层层上抛

        5.2、如果想全部捕获这种嵌套的异常,如何做?   

image

            【分析】:使用throw new Exception,每次捕获异常,便重新包装生成一个异常即可。