.NET Complete

Exception Handling Notes

I only have a few notes this time...

First, What does throw; by itself do?

    try

    {

        try

        {

            try

            {

                try

                {

                    throw new System.IO.FileNotFoundException( );

                }

                catch(System.IO.FileNotFoundException ex)

                {

                    throw;

                }

            }

            catch(Exception ex)

            {

                throw;

            }

        }

        catch

        {

            throw;

        }

    }

    catch(System.IO.FileNotFoundException ex)

    {

        Console.WriteLine(FileNotFoundException exception);

    }

    catch(Exception ex)

    {

        Console.WriteLine(Exception exception);

    }

    catch

    {

        Console.WriteLine(Empty exception...);

    }

The output of this is FileNotFoundException exception, so you can see that throw just rethrows that which was sent to it.  This is true even in the case of the blanket catch statement (try{}catch{}).

What about this?

    try

    {

        throw;

    }

    catch

    {

        throw;

    }

This is a compile error at the first throw; That can only be in a catch block.

Also, the following will not compile.  You have to throw an exception that either is or inherits from System.Exception.  This is something that CLS languages bring to the table.  If you recall from our preview session (the lunch room session) I did a demonstration of assemblies and IL.  IL is the pure .NET language and you are not as constrained in that world.  One example I gave of that was that you don't even need to use a class to start a console application.  You also don't need the entry point name set to main.  In that example I created a simple hello world sample that called a method named asdfasdfadf directly with no classes.  Well, also in IL, you can throw weird things like 4.  It's the compiler that is setting the rules when you go to compile code.

    try

    {

        throw 4;

    }

    catch

    {

        throw;

    }

The last thing I need to mention is something you can see from the first note here.  Exceptions are types and thus are in namespaces.  If you have not set a using statement in your code to bring in the scope of a namespace, you have to access it by the fully qualified class name.