<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>C# Help &#187; Error handling</title>
	<atom:link href="http://www.csharphelp.com/tag/error-handling/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.csharphelp.com</link>
	<description>C# Tutorial and Guides</description>
	<lastBuildDate>Tue, 07 Feb 2012 01:03:28 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Exception Handling Changes in C# 2.0</title>
		<link>http://www.csharphelp.com/2007/09/exception-handling-changes-in-c-2-0/</link>
		<comments>http://www.csharphelp.com/2007/09/exception-handling-changes-in-c-2-0/#comments</comments>
		<pubDate>Thu, 13 Sep 2007 04:01:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C# Language]]></category>
		<category><![CDATA[Error handling]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=665</guid>
		<description><![CDATA[Charlie Calvert asked me to write some C#posts for MSDN C# Developer Center. This article is the first of aseries about the changes from C# 1.0 to C# 2.0. By this I don&#39;t meanenhancements (generics, partial classes, etc), but items that wouldeither cause compile errors, create warnings, or change (presumablyimprove) behavior. I haven&#39;t seen much [...]]]></description>
			<content:encoded><![CDATA[<p><span class="smallblack">Charlie Calvert asked me to write some C#posts for MSDN C# Developer Center. This article is the first of aseries about the changes from C# 1.0 to C# 2.0. By this I don&#39;t meanenhancements (generics, partial classes, etc), but items that wouldeither cause compile errors, create warnings, or change (presumablyimprove) behavior. I haven&#39;t seen much of a comprehensive listing ofthese changes so I decided to try my hand at coming up with one. Intoday&#39;s post I am going to talk about a change in exception handling. </span></p>
<p><span class="smallblack">Consider the following code listing: </span></p>
<p><span class="smallblack">using System;<br />class Program<br />{<br /> static void Main()<br /> {<br /> try<br /> {<br /> Console.WriteLine(<br /> &quot;Hello. My name is Inigo Montoya.&quot;);<br /> }<br /> catch(Exception )<br /> {<br /> // .<br /> }<br /> catch<br /> {<br /> Console.WriteLine(&quot;UNEXPECTED EXCEPTION&quot;);<br /> }<br /> }<br />}<br /></span>
<p><span class="smallblack">In C# 1.0, this code was perfectly valid. However, in C# 2.0 it results in a warning. Why is that? </span></p>
<p><span class="smallblack">An empty catch block (catch{ . }), compilesdown to CIL code that is the equivalent of catch(object ){ . }. Inother words, an empty catch block in C# is a catch block for any andall types that are thrown as exceptions. (Interestingly, C# doesn&#39;tallow you to explicitly code catch(object ){ . }. Therefore, there isno means of catching a non-System.Exception-derived exception and havethe exception instance to scrutinize.) </span></p>
<p><span class="smallblack">It is perhaps surprising that catch(object ){. } is needed because C# doesn&#39;t allow you to throw an exception thatdoesn&#39;t derive from System.Exception. However, the same restrictiondoes not apply to other languages. C++, for example, can throw anobject of any type (whether derived from System.Exception or not). As aresult, in C# 1.0, the only way to ensure that all exceptions werecaught was to include an empty catch block. </span></p>
<p><span class="smallblack">In C# 2.0 the rules improved. Although it isstill possible for other languages to throw exceptions of any type, theCLR will wrap all exceptions that do not derive from System.Exceptioninto a System.Runtime.CompilerServices.RuntimeWrappedException object,which does derive from System.Exception. In other words, allexceptions, whether System.Exception-derived or not when they arethrown, will be caught in C# 2.0 code by a catch(Exception ){ . }block. </span></p>
<p><span class="smallblack">Therefore, if you follow a catch(Exception ){. } block by an empty exception block (as shown in the initial codelisting), the empty exception block will never execute. All exceptionswill be wrapped in the RuntimeWrappedException if they do not derivefrom System.Exception already and therefore be caught bycatch(Exception ){ . }. </span></p>
<p><span class="smallblack">One more thing to note: If you wish your codeto behave as it did with C# 1.0 in this area, you can add theRuntimeCompatibility assembly attribute as in: </span></p>
<p><span class="smallblack">[assembly:System.Runtime.CompilerServices.RuntimeCompatibility(WrapNonExceptionThrows = false)]</span></p>
<p><span class="smallblack">This will no longer produce the warning sinceit will also turn off the new CLR 2.0 behavior in whichnon-System.Exception-derived exceptions are wrapped withRuntimeWrappedException.</span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2007/09/exception-handling-changes-in-c-2-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Use Of InnerException</title>
		<link>http://www.csharphelp.com/2007/03/the-use-of-innerexception/</link>
		<comments>http://www.csharphelp.com/2007/03/the-use-of-innerexception/#comments</comments>
		<pubDate>Sat, 10 Mar 2007 04:01:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C# Language]]></category>
		<category><![CDATA[Error handling]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=478</guid>
		<description><![CDATA[An unknown error withan unknown description has occurred. Please remain calm while the appropriateauthorities are on their way.Do you recognize these kind oferrors? Ever wondered how you can manage your errors in a way you can track &#39;mdown from their source to the point you need to show them? The solution issimple. Use the innerexception [...]]]></description>
			<content:encoded><![CDATA[<p><span class="smallblack"><span style="font-family:Verdana;font-size:small;"><i><span style="color:#ff0000;">An unknown error withan unknown description has occurred. Please remain calm while the appropriateauthorities are on their way.</span></i><span style="color:#008000;"><br /></span></span><span style="font-family:Verdana;font-size:x-small;">Do you recognize these kind oferrors? Ever wondered how you can manage your errors in a way you can track &#39;mdown from their source to the point you need to show them? The solution issimple. Use the <b>innerexception</b> from the standard <span style="font-size:x-small;">ApplicationExceptionobject. In the next example I use a custom Exception because i need someadditional info but it will also work finewith a default Exception.</span></span></span></p>
<p><span class="smallblack"><span style="font-family:Verdana;font-size:x-small;">STEP1: Create my own exception class wichcontains extra properties (sender and details). This class also contains aShowError method that loads a form that will show the error message(s). TheToString is overridden so it can show my extra added information.&nbsp;</span></span></p>
<p><span class="smallblack"><span style="font-family:Courier New;color:#008000;font-size:x-small;"></span></span></p>
<p><span class="smallblack"><span style="font-family:Courier New;color:#008000;font-size:x-small;">//&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />//<br />// Author : Loek van den Ouweland<br />// EMail&nbsp; : <a href="mailto:lvdo@in2net.nl">lvdo@in2net.nl</a><br />// Creation date : July 2003<br />//<br />//&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br /></span><span style="font-family:Courier New;font-size:x-small;"><span style="color:#0000ff;">using</span> System;<br /><span style="color:#0000ff;">using</span> System.Windows.Forms;</p>
<p><span style="color:#0000ff;">namespace</span> LootAtThisError<br />{<br />&nbsp;&nbsp;&nbsp; <span style="color:#0000ff;">public class</span> LookException : ApplicationException<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color:#0000ff;">private string</span> mSender;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color:#0000ff;">private string</span> mDetails;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color:#0000ff;">public</span>LookException (string message, Exception ex, string sender, string details) : base (message,ex)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; mSender=sender;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; mDetails=details;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }&nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color:#0000ff;">public string</span> Sender<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color:#0000ff;">get</span>{<span style="color:#0000ff;">return</span> mSender;}<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color:#0000ff;">public string</span> Details<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color:#0000ff;">get</span>{<span style="color:#0000ff;">return</span> mDetails;}<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br /><span style="font-family:Courier New;font-size:x-small;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color:#0000ff;">public void</span> ShowError()<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; FExceptionfe=<span style="color:#0000ff;">new</span> FException(this);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; fe.ShowDialog();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color:#0000ff;">public override</span><span style="color:#0000ff;"> string</span> ToString()<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color:#0000ff;">string</span> errortext=&quot;Message: &quot; + this.Message + Environment.NewLine +<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &quot;Sender : &quot; + mSender + Environment.NewLine +<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &quot;Details: &quot; + mDetails + Environment.NewLine;</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color:#0000ff;">return</span> errortext;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }&nbsp;<br />&nbsp;&nbsp;&nbsp; }</p>
<p>}<br /></span></span></p>
<p><span class="smallblack"><span style="font-family:Verdana;font-size:x-small;">STEP2: The first error that will appear isalways of type: Exception. Just catch this bad boy and throw your own:</span></span></p>
<p><span class="smallblack"><span style="font-family:Courier New;font-size:x-small;"><span style="color:#0000ff;">string</span>sql=&quot;this will certainly raise an arror&quot;;<br /></span>.<br />.<span style="font-family:Courier New;color:#0000ff;font-size:x-small;"><br />catch</span><span style="font-family:Courier New;font-size:x-small;"> (Exception ex)<br />{<br /></span><span style="font-family:Courier New;color:#0000ff;font-size:x-small;">&nbsp;&nbsp; </span> <span style="font-family:Courier New;color:#0000ff;font-size:x-small;">throw</span><span style="font-family:Courier New;font-size:x-small;"></span><span style="font-family:Courier New;color:#0000ff;font-size:x-small;">new</span><span style="font-family:Courier New;font-size:x-small;"></span><span style="font-family:Courier New;font-size:x-small;">LookException </span><span style="font-family:Courier New;font-size:x-small;">(ex.Message,ex,ex.Source,sql);<br />}</span></span></p>
<p><span class="smallblack"><span style="font-size:x-small;">
<p><span style="font-family:Verdana;font-size:x-small;">STEP3: Just catch and rethrow your error asmany times as you want. These are </span><span style="font-family:Courier New;font-size:x-small;">LookException</span><span style="font-family:Courier New;">s</span><span style="font-family:Verdana;font-size:x-small;">:</span></p>
<p></span></span></p>
<p><span class="smallblack"><span style="font-family:Courier New;color:#0000ff;font-size:x-small;">catch</span><span style="font-family:Courier New;font-size:x-small;">(</span><span style="font-family:Courier New;font-size:x-small;">LookException </span><span style="font-family:Courier New;font-size:x-small;">ex)<br />{<br />&nbsp;&nbsp; </span> <span style="font-family:Courier New;color:#0000ff;font-size:x-small;">throw</span><span style="font-family:Courier New;font-size:x-small;"></span><span style="font-family:Courier New;color:#0000ff;font-size:x-small;">new</span><span style="font-family:Courier New;font-size:x-small;"></span><span style="font-family:Courier New;font-size:x-small;">LookException </span><span style="font-family:Courier New;font-size:x-small;">(&quot;myfriendly error message&quot;,ex,&quot;it happened here&quot;,&quot;extra detailslike ID&#39;s&quot;);<br />}</span></span></p>
<p><span class="smallblack"><span style="font-size:x-small;"></span></span></p>
<p><span class="smallblack"><span style="font-size:x-small;"><span style="font-family:Verdana;font-size:x-small;">STEP4: At last, i.e. in your presentationlayer, just catch the </span><span style="font-family:Courier New;font-size:x-small;">LookException</span><span style="font-family:Courier New;">and show the error</span><span style="font-family:Verdana;font-size:x-small;">:</span></span></span></p>
<p><span class="smallblack"><span style="font-size:x-small;"><span style="font-family:Courier New;"><span style="color:#0000ff;font-size:x-small;">catch</span> (</span><span style="</p>
<p>font-fam<br />
ily:Courier New;font-size:x-small;">LookException</span><span style="font-family:Courier New;">ex)<br />{<br />&nbsp;&nbsp;&nbsp; ex.ShowError();<br />}</span></span></span></p>
<p><span class="smallblack"><span style="font-size:x-small;"><span style="font-family:Courier New;"><span style="color:#0000ff;font-size:x-small;">catch</span>(Exception ex)<br />{<br />&nbsp; // also: always catch a default Exception just to make sure no-oneescapes!<br />}</span></span></span></p>
<p><span class="smallblack"><span style="font-size:x-small;"><span style="font-family:Verdana;font-size:x-small;">STEP5: Create a form that&#39;s capable of showingthe error. To show the error with all it&#39;s innerexceptions, pass the exceptionto the form (store it in mException) and do something like this:</span></span></span></p>
<p><span class="smallblack"><span style="font-size:x-small;"><span style="font-family:Courier New;"><span style="color:#0000ff;font-size:x-small;">private</span> <span style="color:#0000ff;font-size:x-small;">void</span>FException_Load(<span style="color:#0000ff;font-size:x-small;">object</span> sender,System.EventArgs e)<br />{<br />&nbsp;&nbsp;&nbsp; txtMessage.Text=mException.Message;<br />&nbsp;&nbsp;&nbsp; Exception inex=mException;<br />&nbsp;&nbsp;&nbsp; <span style="color:#0000ff;font-size:x-small;">while</span> (inex!=<span style="color:#0000ff;font-size:x-small;">null</span>)<br />&nbsp;&nbsp; </span></span> <span style="font-family:Courier New;"><span style="font-size:x-small;">{<br />&nbsp;&nbsp; </span></span>&nbsp;&nbsp;&nbsp;&nbsp; <span style="font-family:Courier New;"><span style="font-size:x-small;">txtDetails.Text+=inex.ToString() + Environment.NewLine;<br />&nbsp;&nbsp; </span></span>&nbsp;&nbsp;&nbsp;&nbsp; <span style="font-family:Courier New;"><span style="font-size:x-small;">txtDetails.Text+=Environment.NewLine + &quot;&lt;*==&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;==*&gt;&quot; +Environment.NewLine;<br /></span></span><span style="font-family:Courier New;font-size:x-small;">&nbsp;&nbsp; </span>&nbsp;&nbsp;&nbsp;&nbsp;<span style="font-family:Courier New;"><span style="font-size:x-small;">inex=inex.InnerException;<br />&nbsp;&nbsp; </span></span> <span style="font-size:x-small;"><span style="font-family:Courier New;">}<br />}</span></span></span></p>
<p><span class="smallblack"><span style="font-size:x-small;"><span style="font-family:Verdana;font-size:x-small;">CONCLUSION: The trick here is that every timeyou throw an error, you can pass the &#39;just catched&#39; error along with it. </span><span style="font-family:Verdana;">Finallyshow the exception plus all innerexceptions by calling their ToString-functions.Happy catching!</span></span></span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2007/03/the-use-of-innerexception/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Handling Exceptions in C#</title>
		<link>http://www.csharphelp.com/2006/09/handling-exceptions-in-c/</link>
		<comments>http://www.csharphelp.com/2006/09/handling-exceptions-in-c/#comments</comments>
		<pubDate>Mon, 25 Sep 2006 04:01:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C# Language]]></category>
		<category><![CDATA[Error handling]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=312</guid>
		<description><![CDATA[Exceptions are errors that may occur duringthe run-time of a program. Exception handling, thus, becomes anintegral part of programming. In C#, exceptions are handled via theException base class. You can also create your own Exception class but,which will, necessarily, derive from the base, inbuilt Exception class. An exception is, for example, a &#34;divide byzero operation&#34;, [...]]]></description>
			<content:encoded><![CDATA[<p><span style="font-size:xx-small;"><b><br /></b></span><span class="smallblack"><a href="mailto:jvravichandran@yahoo.com"></a></span></p>
<p><span class="smallblack">Exceptions are errors that may occur duringthe run-time of a program. Exception handling, thus, becomes anintegral part of programming. In C#, exceptions are handled via theException base class. You can also create your own Exception class but,which will, necessarily, derive from the base, inbuilt Exception class.</span></p>
<p><span class="smallblack">An exception is, for example, a &quot;divide byzero operation&quot;, which will result in a faulty or a needless result andhence, needs to be handled in a program. An exception can also be,&quot;IndexOutOfBounds&quot;, which arises out when your program tries to accessa non-existent element in an array say, 101, in an array of max size100. There are many such inbuilt exceptions that are handled by theException base class but, since logic is about possibilities, thepossibility of an unhandled exception may arise and to know how tocreate your own exception class to handle such a calamity is thepurpose of this article.</span></p>
<p><span class="smallblack">The following is a program that defines my own Exception class.</span></p>
<p><span class="smallblack">using System;<br />public class MyException:Exception<br />{<br />public string s;<br />public MyException():base()<br />{<br />s=null;<br />}<br />public MyException(string message):base()<br />{<br />s=message.ToString();<br />}<br />public MyException(string message,Exception myNew):base(message,myNew)<br />{<br />s=message.ToString();// Stores new exception message into class member s<br />}<br />public static void Test()<br />{<br />string str,stringmessage;<br />bool flag=false;<br />stringmessage=null;<br />char ch=&#39; &#39;;<br />int i=0;<br />Console.Write(&quot;Please enter some string (less than 27 characters) &#8211; &quot;);<br />str=Console.ReadLine();<br />try{<br />ch=str[i];<br />while (flag==false)<br />{<br />if (ch==&#39;\r&#39;)<br />{<br />flag=true;<br />}<br />else{<br />ch=str[i];<br />i++;<br />}<br />}<br />}<br />catch(Exception e){<br />flag=true;<br />}</p>
<p>if (i&gt;27)<br />{<br />stringmessage=&quot;You cannot enter more than 27 characters !&quot;;<br />throw new MyException(stringmessage);<br />}<br />}<br />public static void Main()<br />{<br />try<br />{<br />Test();<br />}<br />catch(MyException e)<br />{<br />Console.WriteLine(e.s);<br />}<br />}<br />}<br /></span>
<p><span class="smallblack">The above program creates a new exceptionclass called MyException, which derives from the base Exception class.The class has three constructors &#8211; one, default and two overloadedconstructors. The intention is simple &#8211; to be able to overload aconstructor of the base class, the base class&#39; default or existingconstructors must be implemented in the deriving class and thenoverload the relevant constructor. But, the real purpose of the classis to handle an exception &#8211; if the user enters more than 27 characters,then a message prompting the user of the error is to be displayed.Although, this is not really an exception, such an instance is actuallycalled Validation of data but, for want of an example, such anoccurrence has been used for exception handling. The new exceptionMyException is thrown from the Test() method and the message &#8211; &quot;Youcannot enter more than 27 characters !&quot; &#8211; is passed to the class, whichis retrieved by the catch block in the Main() method !</span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2006/09/handling-exceptions-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C# Debugging</title>
		<link>http://www.csharphelp.com/2006/05/c-debugging/</link>
		<comments>http://www.csharphelp.com/2006/05/c-debugging/#comments</comments>
		<pubDate>Sat, 27 May 2006 04:01:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C# Language]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[Error handling]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=191</guid>
		<description><![CDATA[Debugging GUI applications for me mostlyconsists of printing out debug statements in the form of a dialog boxwith some text. While this technique was helpful for small to mediumsize apps I find writing large apps with a dialog box popping up afterevery other statement is counterproductive. With this in mind, I setout to find a [...]]]></description>
			<content:encoded><![CDATA[<p><span style="font-size: xx-small;"><strong><br />
</strong></span><span class="smallblack"><a href="mailto:MikeD227@hotmail.com"></a></span></p>
<p><span class="smallblack">Debugging GUI applications for me mostlyconsists of printing out debug statements in the form of a dialog boxwith some text. While this technique was helpful for small to mediumsize apps I find writing large apps with a dialog box popping up afterevery other statement is counterproductive. With this in mind, I setout to find a better method for displaying debug statements duringruntime. Enter C#. </span></p>
<p><span class="smallblack">C# solves three problems I faced whendesigning the useful and scalable debugging system. These problemsexist either in Java, C/C++, or both (my main programming languages). </span></p>
<p><span class="smallblack">1.	Not having very much meta-information (e.g. line number, method name, etc.)<br />
2.	Having to add and remove debug statements whenever the debug focus shifts<br />
3.	Having the debug statements compiled into the program affecting performance</span></p>
<p><span class="smallblack">Ok, discussing the solution for these problemsin order we&#8217;ll start with number one. Basically a few classes from theSystem.Reflection and System.Diagnostics namespaces solve this problem.Using the System.Diagnostics.StackFrame class the call stack can beexplored and stack details such as what is on the stack level above thecurrent one, what line is a function being called from, etc. And withthe System.Reflection classes the names of functions, namespaces,variable types, etc., can be ascertained. Applying all this to theproblem at hand here&#8217;s some code that retrieves the file name, linenumber, and method name of the function that called it.</span></p>
<p><span class="smallblack">// create the stack frame for the function that called this function<br />
StackFrame sf = new StackFrame( 1, true );</span></p>
<p>// save the method name<br />
string methodName = sf.GetMethod().ToString();</p>
<p>// save the file name<br />
string fileName = sf.GetFileName();</p>
<p>// save the line number<br />
int lineNumber = sf.GetFileLineNumber();</p>
<p><span class="smallblack">Moving right along to problem number two let&#8217;sdiscuss how to selectively debug different sections of a program duringruntime. Number two ties in with number one in that information fromnumber one will help us filter debug statements from being displayed.For this example we&#8217;ll filter by namespace. So say that you havefifteen namespaces in your program and right now you only want todisplay debug statements from one all you would have to do is tell thedebug class only allow that one namespace to display debug statements.Simple enough. Here&#8217;s some code.</span></p>
<p><span class="smallblack">// create the namespaces hashtable<br />
namespaces = new Hashtable();</span></p>
<p>// get the assembly of this class<br />
Assembly a = Assembly.GetAssembly( new Debug().GetType() );</p>
<p>// now cycle through each type and gather up all the namespaces<br />
foreach( Type type in a.GetTypes() )<br />
{<br />
// check if the namespace is already in our table<br />
if( ! namespaces.Contains( type.Namespace ) )<br />
namespaces.Add( type.Namespace, true );<br />
}</p>
<p><span class="smallblack">The above code will create a Hashtable objectcontaining all the namespaces in the same assembly as the Debug classof which this code is a part. Of course, this is only half of thesolution so here is the actual filtering code.</span><br /><i>Continues&#8230;</i></p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2006/05/c-debugging/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C# Exceptions and the Exception Stack</title>
		<link>http://www.csharphelp.com/2006/05/c-exceptions-and-the-exception-stack/</link>
		<comments>http://www.csharphelp.com/2006/05/c-exceptions-and-the-exception-stack/#comments</comments>
		<pubDate>Tue, 09 May 2006 04:01:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C# Language]]></category>
		<category><![CDATA[Error handling]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=173</guid>
		<description><![CDATA[A bit about Exceptions C# has introduced possibly the best tool to use for application error trapping: The exception. An exception is an error condition that is raised whenever your application misbehaves or identifies a problemthat needs to be dealt with right away. This tutorial requires that youhave a basic understanding of C# (or Java) [...]]]></description>
			<content:encoded><![CDATA[<p><strong>A bit about Exceptions</strong></p>
<p><span class="smallblack">C# has introduced possibly the best tool to use for application error trapping: The exception. An exception is an error condition that is raised whenever your application misbehaves or identifies a problemthat needs to be dealt with right away. This tutorial requires that youhave a basic understanding of C# (or Java) exceptions and that you haveused them a few times in your code. </span></p>
<p><span class="smallblack">The purpose of this tutorial is to explainfirstly how you would go about creating your own set of exceptions totrap error conditions that could occur in your code or library, foryour own benefit or for the benefit of another developer using yourlibrary. The second lesson is on how the C# exception stack works, and how you can use it to catch all types of exceptions.</span></p>
<p><span class="smallblack"> Let&#8217;s Begin!</span></p>
<p><span class="smallblack"><strong>The C# Exception Stack</strong><br />
Everyexception that is defined within the .NET framework derives from aclass called Exception. This class is used to describe a general error,whose specificity is not known. For example, a general exception could be an error that is not related in any way to errors that can occurfrom a library you are using.</span></p>
<p><span class="smallblack"> Every exception inherits from the base class Exception in order to provide a more specific response to the developer. A SocketException indicated to the developer that something went wrong while he was trying to perform an operation with the Socketclass or one of it&#8217;s children. There could be a further child exception called TCPStreamException, derived from SocketException, which describes error conditions relating to the transmission of streamed data across a socket.</span></p>
<p><span class="smallblack"> The result of this inherited characteristicis that you can set up an exception stack to trap errors, starting fromthe most-specific error possible to the least-specific known error.This means that a developer, when performing TCPStream operations, must trap for possible exceptions in the following order: TCPStreamException-&gt; SocketException -&gt; Exception. This will allow him to trap all possible errors, and act intellengently according to the type of exception encountered.</span></p>
<p><span class="smallblack"> In my example source code, I have three exceptions. From parent to child:</span></p>
<p><span class="smallblack">Exception-&gt;VehicleException -&gt;MotorCarException-&gt; FerrariException. This follows the classicobject inheritance example ofObject-&gt;Vehicle-&gt;MotorCar-&gt;Ferrari. Can you see how each exception object has a direct connection to the physical object itraises an error for? Examine the source code in the CheckCar class andyou will see the order that each exception is trapped.</span></p>
<p><span class="smallblack"><strong>Creating your own Exceptions in C#</strong><br />
Thisbecomes a very useful tool when you start creating libraries of code tobe used in your application. Each library which is built to perform aspecific task, should have it&#8217;s own set of exceptions that alert thedeveloper of error conditions that can arise when the library is used.&lt;br /&gt;&lt;em&gt;Continues&#8230;&lt;/em&gt;&lt;br /&gt;&lt;br /&gt;&lt;!&#8211;nextpage&#8211;&gt; </span></p>
<p><span class="smallblack"> For example, if you have a library thatparses a string, but cannot accept the character &#8216;&amp;&#8217;. You wouldthen create an exception called BadCharacterException which will bethrown each time the application tries to parse a string containing the&#8217;&amp;&#8217; character. </span><br /><i>Continues&#8230;</i></p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2006/05/c-exceptions-and-the-exception-stack/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C# Exception Handling</title>
		<link>http://www.csharphelp.com/2006/04/c-exception-handling/</link>
		<comments>http://www.csharphelp.com/2006/04/c-exception-handling/#comments</comments>
		<pubDate>Sat, 29 Apr 2006 04:01:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C# Language]]></category>
		<category><![CDATA[Error handling]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=163</guid>
		<description><![CDATA[Definition:&#34;EXCEPTION IS A RUNTIME ERROR WHICH ARISES BECAUSE OF ABNORMALCONDITION INA CODE SEQUENCE. &#34; In C# Exception is a class in the systemnamespace. An object of an exception is that describe the exceptionalconditions occur in a code That means, we are catching an exception,creating an object of it, and then throwing it. C# supports exceptionsin [...]]]></description>
			<content:encoded><![CDATA[<p><span style="font-size:xx-small;"><b><br /></b></span><span class="smallblack"><a href="http://www.csharphelp.com/bio/kamran.html"></a></span></p>
<p><span class="smallblack">Definition:&quot;EXCEPTION IS A RUNTIME ERROR WHICH ARISES BECAUSE OF ABNORMALCONDITION INA CODE SEQUENCE. &quot; In C# Exception is a class in the systemnamespace. An object of an exception is that describe the exceptionalconditions occur in a code That means, we are catching an exception,creating an object of it, and then throwing it. C# supports exceptionsin a very much the same way as Java and C++. </span></p>
<p><span class="smallblack">Before going into detail, I must say the usefulness of knowing and performing exception handling :</span></p>
<p><span class="smallblack">?	They cannot be ignored, as if calling code does not handle the error, it causes program termination.<br />? They do not need to be to be handled at the point where error tookplace. This makes them very suitable for library or system code, whichcan signal an error and leave us to handle it <br />?	They can be used when passing back a return value cannot be used. </span></p>
<p><span class="smallblack">Exceptions are handled by using try?catchstatements. Code which may give rise to exceptions is enclosed in a tryblock , which is followed by one or more catch blocks. Well if we don&#39;twrite like such we get errors like as follows :</span></p>
<p>&nbsp;</p>
<p><span class="smallblack">class A {<br /> static void Main() {<br /> catch {<br /> }<br /> }<br />} </p>
<p>TEMP.cs(3,5): error CS1003: Syntax error, &#39;try&#39; expected </p>
<p>class A {<br /> static void Main() {<br /> finally {<br /> }<br /> }<br />} </p>
<p>TEMP.cs(3,5): error CS1003: Syntax error, &#39;try&#39; expected </p>
<p>class A {<br /> static void Main() {<br /> try {<br /> }<br /> }<br />} <br /></span>
<p><span class="smallblack">TEMP.cs(6,3): error CS1524: Expected catch or finally </span></p>
<p><span class="smallblack">The try block contains the code segmentexpected to raise an exception. This block is executed until anexception is thrown The catch block contains the exception handler.This block catches the exception and executes the code written in theblock. If we do not know what kind of exception is going to be thrownwe can simply omit the type of exception. We can collect it inException object as shown in the following program: </span></p>
<p>&nbsp;</p>
<p><span class="smallblack">int a, b = 0 ;<br />Console.WriteLine( &quot;My program starts &quot; ) ;<br />try<br />{ <br /> a = 10 / b; <br />} <br />catch ( Exception e )<br />{ <br /> Console.WriteLine ( e ) ; <br />} <br />Console.WriteLine ( &quot;Remaining program&quot; ) ; <br /></span>
<p><span class="smallblack">The output of the program is: </span></p>
<p><span class="smallblack">My program starts<br />System.DivideByZeroException: Attempted to divide by zero.atConsoleApplication4.Class1.Main(String[] args) in d:\dont delete\c#(csharp)\swapna\programs\consoleapplication4\consoleapplication4\class1.cs:line51<br />Remaining program </span></p>
<p><span class="smallblack">The exception &#39;Divide by zero&#39; was caught, butthe execution of the program did not stop. There are a number ofexception classes provided by C#, all of which inherit from theSystem.Exception class. Following are some common exception classes. </span></p>
<p>
<table border="1" cellpadding="3" cellspacing="0">
<tbody>
<tr>
<td class="smallestblack">Exception Class</td>
<td class="smallestblack">Cause</td>
</tr>
<tr>
<td class="smallestblack">SystemException </td>
<td class="smallestblack">A failed run-time check;used as a base class for other. </td>
</tr>
<tr>
<td class="smallestblack">AccessException </td>
<td class="smallestblack">Failure to access a type member, such as a method or field. </td>
</tr>
<tr>
<td class="smallestblack">ArgumentException </td>
<td class="smallestblack">An argument to a method was invalid. </td>
</tr>
<tr>
<td class="smallestblack">ArgumentNullException </td>
<td class="smallestblack">A null argument was passed to a method that doesn&#39;t accept it.</td>
</tr>
<tr>
<td class="smallestblack">ArgumentOutOfRangeException </td>
<td class="smallestblack">Argument value is out of range. </td>
</tr>
<tr>
<td class="smallestblack">ArithmeticException </td>
<td class="smallestblack">Arithmetic over &#8211; or underflow has occurred. </td>
</tr>
<tr>
<td class="smallestblack">ArrayTypeMismatchException </td>
<td class="smallestblack">Attempt to store the wrong type of object in an array. </td>
</tr>
<tr>
<td class="smallestblack">BadImageFormatException </td>
<td class="smallestblack">Image is in the wrong format. </td>
</tr>
<tr>
<td class="smallestblack">CoreException </td>
<td class="smallestblack">Base class for exceptions thrown by the runtime.</td>
</tr>
<tr>
<td class="smallestblack">DivideByZeroException </td>
<td class="smallestblack">An attempt was made to divide by zero. </td>
</tr>
<tr>
<td class="smallestblack">FormatException </td>
<td class="smallestblack">The format of an argument is wrong. </td>
</tr>
<tr>
<td class="smallestblack">IndexOutOfRangeException</td>
<td class="smallestblack">An array index is out of bounds. </td>
</tr>
<tr>
<td class="smallestblack">InvalidCastExpression </td>
<td class="smallestblack">An attempt was made to cast to an invalid class. </td>
</tr>
<tr>
<td class="smallestblack">InvalidOperationException </td>
<td class="smallestblack">A method was called at an invalid time. </td>
</tr>
<tr>
<td class="smallestblack">MissingMemberException </td>
<td class="smallestblack">An invalid version of a DLL was accessed. </td>
</tr>
<tr>
<td class="smallestblack">NotFiniteNumberException </td>
<td class="smallestblack">A number is not valid. </td>
</tr>
<tr>
<td class="smallestblack">NotSupportedException </td>
<td class="smallestblack">Indicates sthat a method is not implemented by a class. </td>
</tr>
<tr>
<td class="smallestblack">NullReferenceException </td>
<td class="smallestblack">Attempt to use an unassigned reference. </td>
</tr>
<tr>
<td class="smallestblack">OutOfMemoryException </td>
<td class="smallestblack">Not enough memory to continue execution.</td>
</tr>
<tr>
<td class="smallestblack">StackOverflowException </td>
<td class="smallestblack">A stack has overflown. </td>
</tr>
</tbody>
</table>
<p><span class="smallblack">The finally block is used to do all the cleanup code. It does not support the error message, but all the codecontained in the finally block is executed after the exception israised. We can use this block along with try-catch and only with catchtoo.</span></p>
<p><span class="smallblack">The finally block is executed even if theerror is raised. Control is always passed to the finally blockregardless of how the try blocks exits.</span></p>
<p><span class="smallblack">This is shown in the following example:</span></p>
<p><span class="smallblack">int a, b = 0 ;<br />Console.WriteLine( &quot;My program starts&quot; ) ;<br />try<br />{<br /> a = 10 / b;<br />}<br />catch ( InvalidOperationException e )<br />{<br /> Console.WriteLine ( e ) ;<br />}<br />catch ( DivideByZeroException e)<br />{<br /> Console.WriteLine ( e ) ;<br />}<br />finally<br />{<br /> Console.WriteLine ( &quot;finally&quot; ) ; <br />}<br />Console.WriteLine ( &quot;Remaining program&quot; ) ; <br /></span>
<p><span class="smallblack">The output here is: </span></p>
<p><span class="smallblack">My program starts<br />System.DivideByZeroException: Attempted to divide by zero.<br />at ConsoleApplication4.Class1.Main(String[] args) in d:\dont delete\c# (c sharp)\swapna\programs\consoleapplication4\consoleapplication4\class1.cs:line 51<br />finally<br />Remaining program</span></p>
<p><span class="smallblack">But then what&#39;s the difference? We could have written<br /> Console.WriteLine (&quot;finally&quot;);<br />after the catch block, and not write the finally block at all. Writingfinally did not make much of a difference. Anyway the code writtenafter catch gets executed.<br /> The answer to this is not clear in this program. <br />It will be clear when we see the try-finally and the throw statement.<br />Consider the following code snippet</span></p>
<p>&nbsp;</p>
<p><span class="smallblack">int a, b<br />
= 0 ;<br<br />
 />Console.WriteLine( &quot;My program starts&quot; ) <br />try<br />{<br /> a = 10 / b;<br />}<br />finally<br />{<br /> Console.WriteLine ( &quot;finally&quot; ) ; <br />}<br />Console.WriteLine ( &quot;Remaining program&quot; ) ; <br /></span>
<p><span class="smallblack">Here the output is</span></p>
<p><span class="smallblack"> My program starts<br />Exception occurred: System.DivideByZeroException: Attempted to divideby zero.at ConsoleApplication4.Class1.Main(String[] args) in d:\dontdelete\c# (csharp)\swapna\programs\consoleapplication4\consoleapplication4\class1.cs:line51<br />finally</span></p>
<p><span class="smallblack">Note that &quot;Remaining program&quot; is not printed out. Only &quot;finally&quot; is printed which is written in the finally block. </span></p>
<p><span class="smallblack">The throw statement throws an exception. Athrow statement with an expression throws the exception produced byevaluating the expression. A throw statement with no expression is usedin the catch block. It re-throws the exception that is currently beinghandled by the catch block.</span></p>
<p><span class="smallblack">Consider the following program:</span></p>
<p>&nbsp;</p>
<p><span class="smallblack">int a, b = 0 ;<br />Console.WriteLine( &quot;My program starts&quot; ) ;<br />try<br />{<br /> a = 10 / b;<br />}<br />catch ( Exception e)<br />{<br /> throw <br />}<br />finally<br />{<br /> Console.WriteLine ( &quot;finally&quot; ) ; <br />}<br /></span>
<p><span class="smallblack">The output here is:</span></p>
<p><span class="smallblack">My program starts<br />Exception occurred: System.DivideByZeroException: Attempted to divideby zero.at ConsoleApplication4.Class1.Main(String[] args) in d:\dontdelete\c#(csharp)\swapna\programs\consoleapplication4\consoleapplication4\class1.cs:line55<br />finally</span></p>
<p><span class="smallblack">This shows that the exception is re-thrown.Whatever is written in finally is executed and the program terminates.Note again that &quot;Remaining program&quot; is not printed.</span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2006/04/c-exception-handling/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

