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异常机制让人关注最多的一点就是“效率”问题.其实,这里存在认识上的误区,因为正常控制流程下的代码运行并不会出现问题, ...
随机推荐
- hdu1760博弈SG
A New Tetris Game Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others ...
- hdu4578 线段树 三次方,二次方,一次方的值
Yuanfang is puzzled with the question below: There are n integers, a 1, a 2, -, a n. The initial val ...
- spring <context:annotation-config> 跟 <context:component-scan>诠释及区别
<context:annotation-config> 和 <context:component-scan>的区别 Difference between <context ...
- C# XML序列化方法和常用特性
/* C#对象XML序列化(一):序列化方法和常用特性 .Net Framework提供了对应的System.Xml.Seriazliation.XmlSerializer负责把对象序列化到XML,和 ...
- ConcurrentHashMap源码及分析
ConcurrentHashMap是在jdk1.5版本开始,存在于java.util.concurrent包下.本文主要是针对jdk1.7版本. 由于HashMap是非线程安全的,HashTable虽 ...
- 笨鸟先飞之ASP.NET MVC系列之过滤器(03动作过滤器过滤器)
概念介绍 动作过滤器应该是我们平常工作中需要用到最多的过滤器了,动作过滤器,主要在我们的动作方法执行前后执行. 如果我们需要创建动作过滤器需要实现IActionFilter接口. 我们看到该接口里有两 ...
- H5新手快速入门 简单布局
布局*{ margin: 0; padding: 0;}.quan{ width: 100%; height: 2000px; background: black url("../ima/b ...
- Akka 的Actor
从第一篇Akka笔记的介绍中,我们是从很高的高度去观察Akka工具箱中的Actors.在这篇笔记的第二篇,我们会看一下Actors中的消息部分.而且延续上一次的例子,我们还会使用同样的学生与老师的例子 ...
- Bootstrap表格样式(附源码文件)--Bootstrap
1.表格默认样式 <h4>表格默认样式</h4><table><!--默认样式--> <tr><th>序号</th> ...
- property--staticmethod--classmethod
特性(property): 作为装饰器使用,调用方式从最初的方法调用改变为属性调用 类方法(classmethod):和类进行交互,单不和实例进行交互 在函数中可以不用上传参数 静态方法(static ...