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. HIVE---基于Hadoop的数据仓库工具讲解

    Hadoop: Hadoop是一个由Apache基金会所开发的分布式系统基础架构.用来开发分布式程序.充分利用集群的威力进行高速运算和存储.Hadoop实现了一个分布式文件系统(Hadoop Dist ...

  3. C-多个行内块布局

    1 消除间隔

  4. Sublime 3 打造成 Python/Django IDE开发利器

    Sublime Text 是一款非常强大的文本编辑器, 下面我们介绍如何将 Sublime Text 3 打造成一款 Python/Django 开发利器:   1. 安装 Sublime Text ...

  5. python 发送邮件,未完

    def send_mail(): try: print "send mail..." # handle = smtplib.SMTP('smtp.163.com', 25) # h ...

  6. Oracle 定时查询数据插入新表中(job+存储过程)

    create table EGMAS_COUNT_DATA(TIMES       date not null, COUNT NUMBER(30) not null, SYSTEM_NAME VARC ...

  7. MySQL 高效查询

    在“现场加号&预约排队”项目中,“号贩子排查任务”在线下测试的时候没有问题,但是线上后,由于线上的数据量较大,导致在执行查询的时系统崩溃:后来经过查找,发现写的sql不合理,查出了许多用不到的 ...

  8. ubuntu6.04下安装Eclipse for C/C++ Development

    ubuntu6.04下安装Eclipse for C/C++ Development 首先安装gcc/g++ 需要安装jdk,有的可以尝试安装openjdk. sudo apt-get install ...

  9. 转:C++输入一行字符串的一点小结

    原文链接: http://www.wutianqi.com/?p=1181 大家在学习C++编程时,一般在输入方面都是使用的cin.而cin是使用空白(空格,制表符和换行符)来定字符串的界的.这就导致 ...

  10. 【转】缓存淘汰算法系列之1——LRU类

    原文地址:http://www.360doc.com/content/13/0805/15/13247663_304901967.shtml 参考地址(一系列关于缓存的,后面几篇也都在这里有):htt ...