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异常机制让人关注最多的一点就是“效率”问题.其实,这里存在认识上的误区,因为正常控制流程下的代码运行并不会出现问题, ...
随机推荐
- Windows下Apache添加SSL模块
参考资料:http://www.yuansir-web.com/2011/05/12/hello-world/测试环境:windows2003 32位 + Apache2.4 + PHP5.4 一.准 ...
- Prometheus : 入门
Prometheus 是一个开源的监控系统.支持灵活的查询语言(PromQL),采用 http 协议的 pull 模式拉取数据等特点使 Prometheus 即简单易懂又功能强大. Prometheu ...
- Android 导入引用第三方项目
环境:Android Studio 1.4 1 以源工程形式导入 第一步,导入项目 File--New--Import Module--->设置导入后的项目名称 第二部,在自己工程中添加Depe ...
- ZOJ 1489 HDU1395 2^x mod n = 1 数学
2^x mod n = 1 Time Limit: 2 Seconds Memory Limit:65536 KB Give a number n, find the minimum x t ...
- java web jsp原理图 ,静态包含,动态包含,out与response.getWrite()
jsp原理图 ,静态包含,动态包含,out与response.getWrite()
- open() close()
open() 方法可以查找一个已经存在或者新建的浏览器窗口. 语法: window.open([URL], [窗口名称], [参数字符串]) 每个参数必须用引号 参数说明: URL:可选参数,在窗口中 ...
- SQL SERVER 数据库级联删除
--SQL SERVER 2008R2 级联删除:主子表设置外键关联,当主表数据删除的时候会自动删除子表中对应的数据 --创建主表 create table test_main( ID ,) PRIM ...
- netfilter/iptables和firewalld的关系
1.netfilter 是linux 内核模块,其中包含了大量的内核规则,而要想对这些内核规则进行操作,就需要用户态的工具. iptables和firewalld就是一个用户态的工具. 2.iptab ...
- npm install 时--save-dev和--save的区别
package.json中两个字段含义简介 一直在使用npm包管理器,对于npm install module --save-dev 和 npm install module --save这两个的区别 ...
- 【学习】滚动延迟加载插件scrollLoading用法
今天遇到一个很好用的滚动延迟加载的插件,作者是我的偶象大神张鑫旭,其博客为http://www.zhangxinxu.com/. 以前也写过这种效果,用的是lazyload,不过只能实现图片的加载.而 ...