There are three ways to 'throw' a exception in C#  C#中有三种抛出异常的方式

  1. Use the throw keyword without an identifier    直接使用throw关键字
  2. Use the throw keyword with the original exception    使用throw关键字抛出捕获的异常对象
  3. 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?的更多相关文章

  1. java关于throw Exception的一个小秘密

    目录 简介 throw小诀窍 总结 java关于throw Exception的一个小秘密 简介 之前的文章我们讲到,在stream中处理异常,需要将checked exception转换为unche ...

  2. throw exception

    Throw new CustomerException('Customer message'); // App\Exceptions\Handler.php public function rende ...

  3. throws/throw Exception 异常应用

    throws通常用于方法的声明,当方法中发生异常的时候,却不想在方法中对异常进行处理的时候,就可以在声明方法时, 使用throws声明抛出的异常,然后再调用该方法的其他方法中对异常进行处理(如使用tr ...

  4. [mysql]throw exception

    CREATE PROCEDURE pro_throwException (errorCode char(5), errorMessage text) BEGIN SIGNAL SQLSTATE err ...

  5. C++异常处理:try,catch,throw,finally的用法

    写在前面 所谓异常处理,即让一个程序运行时遇到自己无法处理的错误时抛出一个异常,希望调用者可以发现处理问题. 异常处理的基本思想是简化程序的错误代码,为程序键壮性提供一个标准检测机制. 也许我们已经使 ...

  6. C++异常处理: try,catch,throw,finally的用法

    写在前面 所谓异常处理,即让一个程序运行时遇到自己无法处理的错误时抛出一个异常,希望调用者可以发现处理问题. 异常处理的基本思想是简化程序的错误代码,为程序键壮性提供一个标准检测机制. 也许我们已经使 ...

  7. C++的异常处理之一:throw是个一无是处的东西

    看这篇文章学习C++异常处理的基础知识.看完后,还不过瘾,为什么大家在C++代码中都不用Exception?为什么C++11会引入一些变化? 为什么C++ exception handling需要un ...

  8. CoreCLR on Mac:体验managed exception handling

    C#测试代码: using System; class Program { static void A() { try { Console.WriteLine("Throwing an ex ...

  9. 编写高质量代码改善C#程序的157个建议[用抛异常替代返回错误、不要在不恰当的场合下引发异常、重新引发异常时使用inner Exception]

    前言 自从.NET出现后,关于CLR异常机制的讨论就几乎从未停止过.迄今为止,CLR异常机制让人关注最多的一点就是“效率”问题.其实,这里存在认识上的误区,因为正常控制流程下的代码运行并不会出现问题, ...

随机推荐

  1. 使用Xshell+Xmanager远程监控jvisualvm

    使用jvisualvm的remote方式监控服务器端jvisualvm时,不是很方便,因此通过local方式,应该是正路. 一.服务器端(Linux,最小安装模式,没有图形界面) 1.安装xauth ...

  2. bzoj4033(树上染色)

    树上染色 有一棵点数为N的树,树边有边权.给你一个在0~N之内的正整数K,你要在这棵树中选择K个点,将其染成黑色,并 将其他的N-K个点染成白色.将所有点染色后,你会获得黑点两两之间的距离加上白点两两 ...

  3. Elixir游戏服设计四

    上章说到我们要引入syn https://github.com/ostinelli/syn/ 看过文档,它并没有直接提供{via, Module, Name} 相关的方法.我们需要封装一下. Name ...

  4. commons-pool与commons-pool2连接池

    commons-pool和commons-pool2是用来建立对象池的框架,提供了一些将对象池化必须要实现的接口和一些默认动作.对象池化之后可以通过pool的概念去管理其生命周期,例如对象的创建,使用 ...

  5. Android 性能优化概念(1)

    http://www.open-open.com/lib/view/open1421723359718.html#_label0 阅读目录 0)Render Performance 1)Underst ...

  6. 2017年十大奇葩画风的H5页面案例,原来脑洞可以这样大

    每个人都是视觉动物,画面精美.体验奇特的H5,用户在内心一般都会满分打出,毫不吝啬,同时也毫不犹豫分享,因为此时的分享不掉价儿~ 今天给大家准备了十支H5,画风超级奇特,非常值得一看所有案例均可在19 ...

  7. JavaScript中的this基本问题

    在函数中 this 到底取何值,是在函数真正被调用执行的时候确定下来的,函数定义的时候确定不了. 执行上下文环境 : **定义**:执行函数的时候,会产生一个上下文的对象,里面保存变量,函数声明和th ...

  8. win10 UWP GET Post

    win10 应用应该是要有访问网络,网络现在最多的是使用GET,Post,简单的使用,可以用网络的数据:获得博客的访问量. 在使用网络,我们需要设置Package.appxmanifest 网络请求使 ...

  9. win10 uwp 拖动控件

    我们会使用控件拖动,可以让我们做出好看的动画,那么我们如何移动控件,我将会告诉大家多个方法.其中第一个是最差的,最后的才是我希望大神你去用. Margin 移动 我们可以使用Margin移动,但这是w ...

  10. 数据挖掘 ID3

    本文讲的是数据挖掘中的ID3,这个有很多人做了,我也没有说什么改善,只是要考试,用我考试记录的来写,具有很大主观性,如果看到有觉得不对或感觉不好,请关掉浏览器或和我说,请不要生气或发不良的言论. 决策 ...