#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)
                    using (StreamReader sr = new StreamReader(args[0]))
                        string firstLine = sr.ReadLine();
                catch (System.Exception exc)

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



About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: