O'Reilly logo

C# 5.0 Unleashed by Bart De Smet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required