#854 – Catching an Exception

You can catch an exception by using the combination of a try block and one or more catch clauses.  If any of the statements within the try block throws an exception and the exception type matches what is specified in the catch clause, the code within the catch clause will execute.

In the example below, we try reading from a file within a try block and we have a catch clause that handles exceptions of any type (System.Exception).  The using block disposes of the StreamReader object properly.

            static void Main(string[] args)
            {
                try
                {
                    using (StreamReader sr = new StreamReader(args[0]))
                    {
                        string firstLine = sr.ReadLine();
                        Console.WriteLine(firstLine);
                    }
                }
                catch (System.Exception exc)
                {
                    Console.WriteLine(exc.GetType());
                    Console.WriteLine(exc.Message);
                }
                Console.ReadLine();
            }
        }

If we run this code and pass in a non-existent file name, we see that we catch an exception of type FileNotFoundException.

854-001

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #854 – Catching an Exception

  1. Pingback: #883 – Re-throwing an Exception | 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: