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异常机制让人关注最多的一点就是“效率”问题.其实,这里存在认识上的误区,因为正常控制流程下的代码运行并不会出现问题, ...
随机推荐
- PHP通过URL获取文件大小
function getFileSize($url){ $url = parse_url($url); if($fp = @fsockopen($url['host'],empty($url['por ...
- 从入门到精通之Boyer-Moore字符串搜索算法详解
本文讲述的是Boyer-Moore算法,Boyer-Moore算法作为字符串搜索算法,兴趣之下就想了解这个算法,发现这个算法一开始还挺难理解的,也许是我理解能力不是很好吧,花了小半天才看懂,看懂了过后 ...
- SVN初体验
呐,部门领导要求今后项目部分内容要实行版本控制,因此有机会深入接触下SVN这门功课 ---------------------------------------------------------- ...
- REST架构概述
REST概述 REST(英文:Representational State Transfer,简称REST)描述了一个架构样式的网络系统,比如 web 应用程序.它首次出现在 2000 年 Roy F ...
- 【转】 Python subprocess模块学习总结
从Python 2.4开始,Python引入subprocess模块来管理子进程,以取代一些旧模块的方法:如 os.system.os.spawn*.os.popen*.popen2.*.comman ...
- MySQL(十五)之数据备份中mysqldump详解
前言 其实前面一篇数据备份已经是非常的详细了,这里我想单独的讲解一下mysqldump,相信很多程序员都是用过这个命令的! 一.MySQL数据库的备份与还原 1.1.MySQL数据库备份 1)语法 m ...
- 每天十分钟系列:JS数据操作之神奇的map()
Array.prototype.map() map()方法可以创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果. demo1 上面的例子,在控制台中打印的结果是: 1 2 3 ...
- mysql登录出现1045错误修改方法
在cmd中输入mysql -uroot -p出现1045错误如下: ERROR 1045(28000): Access denied for user 'root'@'localhost'(using ...
- Android进程间通信
http://www.cnblogs.com/manuosex/p/3588634.html 一.Linux系统进程间通信有哪些方式? 1.socket: 2.name pipe命名管道: 3.mes ...
- Single Number2
题目链接:http://oj.leetcode.com/problems/single-number-ii/ Given an array of integers, every element app ...