Three ways to throw exception in C#. Which is your preference?
There are three ways to 'throw' a exception in C# C#中有三种抛出异常的方式
- Use the throw keyword without an identifier 直接使用throw关键字
- Use the throw keyword with the original exception 使用throw关键字抛出捕获的异常对象
- Use the throw keyword with a new exception 使用throw关键字抛出一个自定义的对像
The first option will rethrow the exception without modifying the call stack. This option should be used when you don’t want any modifications to the exception
第一种方法会直接把当前捕获异常抛出,并保留原始异常的stacktrace
class Program
{
static void Main(string[] args)
{
try
{
new Test().Raise();
}
catch(Exception ex)
{
throw;
}
}
} public class Test
{ public void Raise()
{
throw new Exception("");
}
}
In this example, the ex.StackTrace contains the information came from the original exception. So you can debug the error easier. The stacktrace is
at ConsoleApplication1.Test.Raise() in d:\Project\Test\ConsoleApplication1\ConsoleApplication1\Program.cs:line
at ConsoleApplication1.Program.Main(String[] args) in d:\Project\Test\ConsoleApplication1\ConsoleApplication1\Program.cs:line
If you are working on debug environment, the complier gives you a clarified information about in which line the exception is threw.
When you choose the second option, you reset the call stack to the current location in code
class Program
{
static void Main(string[] args)
{
try
{
new Test().Raise();
}
catch(Exception ex)
{
throw ex;
}
}
} public class Test
{ public void Raise()
{
throw new Exception("");
}
}
In this example, the ex.StackTrace is
at ConsoleApplication1.Program.Main(String[] args) in d:\Project\Test\ConsoleApplication1\ConsoleApplication1\Program.cs:line
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
Compared the result with the previous one, you should find that line 34 is disappeared. But the two examples are almost same except‘throw ex’in the second example and ‘throw’ in the first example in the same line. So you can’t see where the exception originally came from. It is terrible for a developer who has been so crazy in dealing with the modification because of the changed requirements
. But in C# 5, there is a new feature to give you a additional option to throw a exception and preserve the original stack trace. You can use ExceptionDispatchInfo.Throw (another syntactic sugar or something like that? Whatever encapsulated or wrapper methods are always useful
)
Using the third option can be useful when you want to raise another exception to the caller of your code. Nothing to say about it because it is very easy to be understood. You can define a custom exception inherited System.Exception and set the inner exception to the original exception.
Three ways to throw exception in C#. Which is your preference?的更多相关文章
- java关于throw Exception的一个小秘密
目录 简介 throw小诀窍 总结 java关于throw Exception的一个小秘密 简介 之前的文章我们讲到,在stream中处理异常,需要将checked exception转换为unche ...
- throw exception
Throw new CustomerException('Customer message'); // App\Exceptions\Handler.php public function rende ...
- throws/throw Exception 异常应用
throws通常用于方法的声明,当方法中发生异常的时候,却不想在方法中对异常进行处理的时候,就可以在声明方法时, 使用throws声明抛出的异常,然后再调用该方法的其他方法中对异常进行处理(如使用tr ...
- [mysql]throw exception
CREATE PROCEDURE pro_throwException (errorCode char(5), errorMessage text) BEGIN SIGNAL SQLSTATE err ...
- C++异常处理:try,catch,throw,finally的用法
写在前面 所谓异常处理,即让一个程序运行时遇到自己无法处理的错误时抛出一个异常,希望调用者可以发现处理问题. 异常处理的基本思想是简化程序的错误代码,为程序键壮性提供一个标准检测机制. 也许我们已经使 ...
- C++异常处理: try,catch,throw,finally的用法
写在前面 所谓异常处理,即让一个程序运行时遇到自己无法处理的错误时抛出一个异常,希望调用者可以发现处理问题. 异常处理的基本思想是简化程序的错误代码,为程序键壮性提供一个标准检测机制. 也许我们已经使 ...
- C++的异常处理之一:throw是个一无是处的东西
看这篇文章学习C++异常处理的基础知识.看完后,还不过瘾,为什么大家在C++代码中都不用Exception?为什么C++11会引入一些变化? 为什么C++ exception handling需要un ...
- CoreCLR on Mac:体验managed exception handling
C#测试代码: using System; class Program { static void A() { try { Console.WriteLine("Throwing an ex ...
- 编写高质量代码改善C#程序的157个建议[用抛异常替代返回错误、不要在不恰当的场合下引发异常、重新引发异常时使用inner Exception]
前言 自从.NET出现后,关于CLR异常机制的讨论就几乎从未停止过.迄今为止,CLR异常机制让人关注最多的一点就是“效率”问题.其实,这里存在认识上的误区,因为正常控制流程下的代码运行并不会出现问题, ...
随机推荐
- Python数据分析(二): Numpy技巧 (2/4)
numpy.pandas.matplotlib(+seaborn)是python数据分析/机器学习的基本工具. numpy的内容特别丰富,我这里只能介绍一下比较常见的方法和属性. 昨天晚上发了第一 ...
- wxPython中菜单、按钮学习
---恢复内容开始--- wx.Window 是一个基类,许多构件从它继承.包括 wx.Frame 构件.技术上这意味着,我们可以在所有的 子类中使用 wx.Window 的方法.我们这里介绍它的几种 ...
- Lucene介绍与入门使用
Lucene简介 Lucene是apache软件基金会4 jakarta项目组的一个子项目,是一个开放源代码的全文检索引擎工具包,但它不是一个完整的全文检索引擎,而是一个全文检索引擎的架构,提供了完整 ...
- Hibernate操作数据库的回调机制--Callback
1:一般情况下,在使用Hibernate Session存取数据库的代码中,基本上大部分是相同的,如下两个方法所示, //查询Teacher操作 ublic Teacher getTeacher ...
- Linux内存(手动释放cache)
项目的扩容申请了一台机器,到手之后看一下机器的指标,看到内存使用情况是这样的. 1.查看内存 free $ free -h total used free shared buffers cached ...
- NOIP初赛 之 哈夫曼树
哈夫曼树 种根据我已刷的初赛题中基本每套的倒数第五或第六个不定项选择题就有一个关于哈夫曼树及其各种应用的题,占:0-1.5分:然而我针对这个类型的题也多次不会做,so,今晚好好研究下哈夫曼树: 概念: ...
- iKcamp出品|微信小程序|工具安装+目录说明|基于最新版1.0开发者工具初中级教程分享
iKcamp官网:http://www.ikcamp.com 访问官网更快阅读全部免费分享课程:<iKcamp出品|全网最新|微信小程序|基于最新版1.0开发者工具之初中级培训教程分享>. ...
- 框架应用 : Spring MVC - 开发详述
软件开发中的MVC设计模式 软件开发的目标是减小耦合,让模块之前关系清晰. MVC模式在软件开发中经常和ORM模式一起应用,主要作用是将(数据抽象,数据实体传输和前台数据展示)分层,这样前台,后台,数 ...
- Bootstrap 引用的标准模板
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8&quo ...
- MVVM模式下 DataTemplate 中控件的绑定
今天给ListBox中通过DataTemplate生成的Button绑定命令时,一开始Button始终找不到绑定的命令.现找到了正确的绑定方式,特来记录一下. 先上个正确的示例: <ListBo ...