#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