Top

Tags


Roadkill .NET Wiki

Google ads

Recommended reading


Search

Wednesday
Sep092009

3 ways to leave your exception

Below is a small reference showing, by example, the 3 ways of throwing/re-throwing exceptions in C#, and their outcomes.

//
class Program
{
    static void Main(string[] args)
    {
        // Output:
        //
        // Invalid operation: Could not find file 'C:\this doesnt exist.txt'.
        // Could not find file 'C:\this doesnt exist.txt'.
        // Could not find file 'C:\this doesnt exist.txt'.
        //

        try
        {
            ThrowTest.ThrowNew();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

        try
        {
            ThrowTest.Throw();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

        try
        {
            ThrowTest.ThrowEx();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

        Console.ReadLine();
    }
}

public class ThrowTest
{
    public static void ThrowNew()
    {
        try
        {
            File.OpenText(@"C:\this doesnt exist.txt");
        }
        catch (IOException ex)
        {
            // InnerException is null, and the stacktrace starts at ThrowNew()
            throw new InvalidOperationException("Invalid operation: "+ex.Message);
        }
    }

    public static void Throw()
    {
        try
        {
            File.OpenText(@"C:\this doesnt exist.txt");
        }
        catch (IOException ex)
        {
            // This maintains the entire stacktrace, so will include the chain that occured inside the Framework,
            // i.e. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
            throw;
        }
    }

    public static void ThrowEx()
    {
        try
        {
            File.OpenText(@"C:\this doesnt exist.txt");
        }
        catch (IOException ex)
        {
            // InnerException is null, and the stacktrace starts at ThrowEx(). It's the least useful of the three.
            throw ex;
        }
    }
}

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>
« A look at .NET Object Relational Mappers (ORM)s | Main | Const vs Readonly in C# »