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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.