C# Exceptions - Throwing Exceptions
(Page 3 of 4 )
Exceptions can be thrown either by the runtime or in user code. In this example, Display throws a System.ArgumentNullException:
class Test
{
static void Display (string name)
{
if (name == null)
throw new ArgumentNullException ("name");
Console.WriteLine (name);
}
static void Main()
{
try { Display (null); }
catch (ArgumentNullException ex)
{
Console.WriteLine ("Caught the exception");
}
}
}
Rethrowing an exception
You can capture and rethrow an exception as follows:
try { ... }
catch (Exception ex)
{
// Log error
...
throw; // Rethrow same exception
}
Rethrowing in this manner lets you log an error without swallowing it. It also lets you back out of handling an exception should circumstances turn out to be outside what you expected:
using System.Net; // (See Chapter14)
...
string s;
using (WebClient wc = new WebClient())
try { s = wc.DownloadString ("http://albahari.com/"); }
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.NameResolutionFailure)
Console.WriteLine ("Bad domain name");
else
throw; // Can't handle other sorts of WebException, so rethrow
}
The other common scenario is to rethrow a more specific exception type. For example:
try
{
... // parse a date of birth from XML element data
}
catch (FormatException ex)
{
throw new XmlException ("Invalid date of birth", ex);
}
Rethrowing an exception does not affect theStackTraceproperty of the exception (see the next section). When rethrowing a different exception, you can set theInnerExceptionproperty with the original exception if doing so could aid debugging. Nearly all types of exceptions provide a constructor for this purpose.
Next: Key Properties of System.Exception >>
More C# Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of C# 3.0 in a Nutshell, Third Edition, A Desktop Quick Reference, written by Joseph Albahari and Ben Albahari (O'Reilly; ISBN: 0596527578). Check it out today at your favorite bookstore. Buy this book now.
|
|