<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://blogs.msdn.com/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Choosing the Right Type of Exception to Throw</title><link>http://blogs.msdn.com/b/kcwalina/archive/2006/07/05/657268.aspx</link><description>My last post about the ApplicationException resulted in some questions along the lines of “so, if not ApplicationException, what should I throw instead?” The answer to this question is partially covered by my old post on Exception Throwing and partially</description><dc:language>en-US</dc:language><generator>Telligent Evolution Platform Developer Build (Build: 5.6.50428.7875)</generator><item><title>Why catch(Exception)/empty catch is bad</title><link>http://blogs.msdn.com/b/kcwalina/archive/2006/07/05/657268.aspx#9435091</link><pubDate>Fri, 20 Feb 2009 01:42:59 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9435091</guid><dc:creator>CLR Team Blog</dc:creator><description>&lt;p&gt;You’ve seen the advice before— it’s not a good programming practice to catch System.Exception . Because&lt;/p&gt;
&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9435091" width="1" height="1"&gt;</description></item><item><title>C#: throw; vs throw e;</title><link>http://blogs.msdn.com/b/kcwalina/archive/2006/07/05/657268.aspx#5385669</link><pubDate>Tue, 09 Oct 2007 23:12:29 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:5385669</guid><dc:creator>nblog</dc:creator><description>&lt;p&gt;Jakoś ostatnio często wpadają mi do rąk r&amp;#243;żne teksty o wyjątkach w .Net. Z tego co da się zauważyć, to&lt;/p&gt;
&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=5385669" width="1" height="1"&gt;</description></item><item><title>re: Choosing the Right Type of Exception to Throw</title><link>http://blogs.msdn.com/b/kcwalina/archive/2006/07/05/657268.aspx#2461454</link><pubDate>Mon, 07 May 2007 14:02:15 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:2461454</guid><dc:creator>Sundar Rajan</dc:creator><description>&lt;p&gt;Hi,&lt;/p&gt;
&lt;p&gt;In your framework design book you mention that one should avoid throwing COMException since it is for the CLR to throw it.&lt;/p&gt;
&lt;p&gt;We are in the process of writing a data access layer, which is in C#. However the first client of this layer is a COM/C++ application. In order to propagate exceptions from .Net to COM (so that the COM application gets a HResult) we are using COMException. Is this a resonable violation of the guideline, or is there a better way to communicate exception across interop boundaries?&lt;/p&gt;
&lt;p&gt;Thanks&lt;/p&gt;
&lt;p&gt;-Sundar &lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=2461454" width="1" height="1"&gt;</description></item><item><title>推薦一個很棒的 Design Blog. "Krzysztof Cwalina"</title><link>http://blogs.msdn.com/b/kcwalina/archive/2006/07/05/657268.aspx#1665270</link><pubDate>Tue, 13 Feb 2007 03:57:14 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:1665270</guid><dc:creator>Refines.Info["Polo Lee"]</dc:creator><description>&lt;p&gt;為什麼推薦 ? Krzysztof Cwalina 是 .NET Framework API Design Team 的 Program Manager, 他也寫了 一本 Framework Design&lt;/p&gt;
&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=1665270" width="1" height="1"&gt;</description></item><item><title>re: Choosing the Right Type of Exception to Throw</title><link>http://blogs.msdn.com/b/kcwalina/archive/2006/07/05/657268.aspx#1208695</link><pubDate>Tue, 05 Dec 2006 04:45:09 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:1208695</guid><dc:creator>Krzysztof Cwalina</dc:creator><description>&lt;p&gt;Nigel, I think the way to address the abstraction leak is to describe exceptions that can be handled in the contract of the abstraction. Having DataAccessTeamException does not help much: it's not an exception that can be handled, at least not more than System.Exception is.&lt;/p&gt;
&lt;p&gt;John, yes, there are cases where we don't have a good general &amp;quot;it's a bug&amp;quot; exception in the framework, but such cases are extremly rare. In such cases, I would add a new exception, but I would not name it after the team; I would name it so it describes how it's different from existing exceptions in the framework (i.e. describe why you could not throw any of the existing ones). But as I said, it's extremly rare. For example, InvalidOperationException might be a good candidate in cases you described. &lt;/p&gt;
&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=1208695" width="1" height="1"&gt;</description></item><item><title>re: Choosing the Right Type of Exception to Throw</title><link>http://blogs.msdn.com/b/kcwalina/archive/2006/07/05/657268.aspx#1158986</link><pubDate>Mon, 27 Nov 2006 13:03:29 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:1158986</guid><dc:creator>John Waterson</dc:creator><description>&lt;p&gt;Krzysztof, thanks for this guidance, which is invaluable, but I've realised that there is at least one scenario where the guidelines contradict each other. That scenario is when an error condition arises that does NOT match any of the predefined system exceptions, but at the same time does NOT require any specific programmatic handling.&lt;/p&gt;
&lt;p&gt;When would such a scenario occur? Well, for me it happens when I'm baking a fundamental, low-level assumption about an internal data structure into my code, and I cannot imagine any circumstances that would cause the assumption to be violated.&lt;/p&gt;
&lt;p&gt;Now I'm acutely conscious that although I can't IMAGINE any troublesome circumstances, that does NOT mean that they don't exist. And quite often, the code path that would exist IF my assumption were violated is just staring me right in the face.&lt;/p&gt;
&lt;p&gt;Equally often, Bad Things happen on that code path, and unless I'm in an absolutely performance-critical section, I don't feel good about just ignoring it. Obviously I can use Asserts to verify that it will never execute while I'm developing, but what if the assumption gets violated in a release build? My Asserts are useless. It seems negligent NOT to throw an exception, even though I'm pretty sure it will never actually be raised.&lt;/p&gt;
&lt;p&gt;But I don't know how to handle that exception programatically. The circumstances that brought it about are, as I said, unimaginable and therefore by definition I don't know what to do in those circumstances. I just want my code to stop running before it wreaks havoc. &lt;/p&gt;
&lt;p&gt;If I'm following the guidelines strictly then I can't throw Exception, SystemException or ApplicationException. But the assumption that's been violated is often unrelated to parameters or anything else I can articulate using the builtin fine-grained exceptions. Previously I might have created a NameOfMyProjectException and thrown that, just to indicate very clearly that, if the exception is ever raised, then it's a bug. But that's against the guidelines too.&lt;/p&gt;
&lt;p&gt;Any thoughts on what to do in these circumstances?&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=1158986" width="1" height="1"&gt;</description></item><item><title>re: Choosing the Right Type of Exception to Throw</title><link>http://blogs.msdn.com/b/kcwalina/archive/2006/07/05/657268.aspx#1140915</link><pubDate>Fri, 24 Nov 2006 17:01:09 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:1140915</guid><dc:creator>Nigel Armstrong</dc:creator><description>&lt;p&gt;I also think that you need to alter this exception story slightly. Specificially this item:&lt;/p&gt;
&lt;p&gt;&amp;quot;Do not create and throw new exceptions just to have ‘your team's’ exception.&amp;quot;&lt;/p&gt;
&lt;p&gt;If you imagine having a typical multitier application, which has a UI that is going to use data by calling on a method from a data access class. You might have several data access classes (one for XML, one for databases, etc)...the XML reading and writing data access class might have to deal with XmlExceptions, the database one a SqlException. But it shouldn't propagate these back to the UI - instead in my view, your data acess team should create an exception class &amp;quot;the data access team's exception&amp;quot; - eg DataAccessException that is used for all of these classes to report back to the UI that an exception occured. Of course, this exception should set the InnerException correctly so that developers can drill down and see what they did wrong...if you don't do that, then you end up with an &amp;quot;abstraction leak&amp;quot; where the UI has to be aware of what the specific data access technology is being used at that time...&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=1140915" width="1" height="1"&gt;</description></item><item><title>re: Choosing the Right Type of Exception to Throw</title><link>http://blogs.msdn.com/b/kcwalina/archive/2006/07/05/657268.aspx#799068</link><pubDate>Sat, 07 Oct 2006 04:06:21 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:799068</guid><dc:creator>Krzysztof Cwalina</dc:creator><description>&lt;p&gt;Krish, we are thinking about improving the current exceptions story. I agree that what we have today can be way better. We want to strike the right balance without being too rigid (checked exceptions) and too ad-hoc where as you note it's very difficult to write very robust code.&lt;/p&gt;
&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=799068" width="1" height="1"&gt;</description></item><item><title>re: Choosing the Right Type of Exception to Throw</title><link>http://blogs.msdn.com/b/kcwalina/archive/2006/07/05/657268.aspx#776904</link><pubDate>Fri, 29 Sep 2006 16:31:23 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:776904</guid><dc:creator>Krish</dc:creator><description>Hi Krzysztof,

&lt;BrentRector&gt;
As described in more detail later, catching System.Exception is nearly always the wrong thing to do as well.
&lt;/BrentRector&gt;

I agree with you in principle, but the .NET mechanism of not being able to declare exceptions thrown by methods does lead to a lot of headaches. For example, if you properly document your code, you can ensure (not 100% safe) that many people are aware of the possible exceptions that can raised by the code you are calling into. If you don't document your code, well, too bad, and the only other options are to look at the source code (if available) or use ILDasm or some other tool to figure out possible exceptions that can be thrown by the code you're calling into.

I'm not getting into a checked/unchecked exception debate here, but if a method CAN but does [not] have to declare the exceptions that it raises, [and] you add a compiler switch to raise a warning if not declared, that would help methods self-document themselves.

Thoughts?

-krish

For example:

    // legal, but a special compiler flag could raise a warning
    public void M1(Boolean flag)
    {
        if (flag)
            throw new MyException1();
        else
            throw new MyException2();
    }


    // legal, but the special compiler flag could raise a warning for Exception2
    public void M1(Boolean flag) throws Exception1
    {
        if (flag)
            throw new MyException1();
        else
            throw new MyException2();
    }


    // legal, no warnings when using special compiler flag
    public void M1(Boolean flag) throws Exception1, Exception2
    {
        if (flag)
            throw new MyException1();
        else
            throw new MyException2();
    }

In theory, this is similar to Java exceptions that extend from java.lang.RuntimeException (an unchecked exception). Methods that raise the RuntimeException (or sub-classes thereof) can - but do not have to - declare exceptions in the method signature.&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=776904" width="1" height="1"&gt;</description></item><item><title>re: Choosing the Right Type of Exception to Throw</title><link>http://blogs.msdn.com/b/kcwalina/archive/2006/07/05/657268.aspx#705119</link><pubDate>Fri, 18 Aug 2006 05:03:25 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:705119</guid><dc:creator>David Levine</dc:creator><description>I believe there are issues with using custom exceptions that need more guidelines. &lt;br&gt;&lt;br&gt;When the exception thrown will be entirely consumed within the assembly that defines the custom exception then the guidelines above are sufficient (and then it really does not need to be marked as serializable unless explicitly serialized internally)&lt;br&gt;&lt;br&gt;When the custom exception may be thrown across process boundaries, and especially across machine boundaries, then there are other factors that should be considered. The problem is that the entity that receives the exception must have a copy of the assembly that defines the exception to be able to deserialize the exception. If it does not have a copy of the assembly, or if it has the wrong version of the assembly, then a different exception will be thrown by the runtime when it attempts and fails to deserialize the custom exception. This is worse then not using a custom exception because the client will get a misleading exception type to deal with, and any extra data associated with the custom exception will be lost. &amp;nbsp;The ability of an application to correctly interpret and respond to exceptions is of vital importance, and in this situation the abiity to deal meaningfully with custom exception type will be lost or degraded.&lt;br&gt;&lt;br&gt;If this can happen then the custom exception should be mapped at the boundary of the source to an exception defined in a system assembly so that it can be easily consumed. (I feel this is such an important issue that the runtime should provide an automatic mapping service at the receiver to remove this burden from the sender, but that's a different issue).&lt;br&gt;&lt;br&gt;In general, when custom exceptions are exposed to external clients across process and machine boundaries then consideration must be given to the deployment and versioning issues of the assembly in which the custom exception is defined, and if clients will have access to this assembly. If these issues cannot be adequately addressed then consider using standard exceptions instead.&lt;br&gt;&lt;br&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=705119" width="1" height="1"&gt;</description></item></channel></rss>