Friday, April 24, 2015

Make your own variety of exception in C#!

You will write a class that inheirts from ApplicationException. When you throw an exception of your custom shape you may then try to catch your variety of exception first in a try/catch wrapping greater mechanics (inside which the point in code which actually throws your exception is likely deeply nested) before falling over to a more generic catch. That kind of looks like this, but more specifically like:

try
{
   DoSomethingDangerous();
}
catch (FooException fooException)
{
   DoSomethingFooFlavored(fooException);
}
catch (Exception exception)
{
   DoSomethingElse(exception);
}

 
 

There is a parameterless constructor for ApplicationException, but also a handful of parameters. The constructor shaped like...

ApplicationException(string message, System.Exception innerException)
{

 
 

...may in effect define a message and an inner exception handed in from your custom thing shaped like so:

using System;
namespace Whatever
{
   public class FooException : ApplicationException
   {
      public FooException(string bar, Exception baz) : base(bar, baz) { }
   }
}

 
 

Deep in the bowels of the greater stuff wrapped in a try/catch, you'll implement your specific exception in a different try/catch (yes, nested inside of the DoSomethingDangerous logic above) like so:

try
{
   DoSomethingFooSpecific();
}
catch (Exception exception)
{
   throw new FooException("yikes!", exception);
}

No comments:

Post a Comment