Handling Exceptions

Handling exceptions is done by protecting a certain block of code using try and having an exception handler associated with it using catch. You saw examples of this earlier, but let’s take a closer look:

try{    PrintFile(path);}catch (FileNotFoundException ex){    Console.ForegroundColor = ConsoleColor.Red;    Console.WriteLine(ex.Message);    Console.ResetColor();}

Here we’re protecting the call to PrintFile against the FileNotFoundException. Of course, the protected block of code (following the try keyword) can consist of more than one line of code, but it’s a good practice not to protect too much code if you’re only after catching an exception from a specific call somewhere in there.

Note: ...

Get C# 5.0 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.