Catching an exception

Download .net eBook

Example

Code can and should throw exceptions in exceptional circumstances. Examples of this include:

The caller can handle these exceptions by "catching" them, and should only do so when:

  • It can actually resolve the exceptional circumstance or recover appropriately, or;
  • It can provide additional context to the exception that would be useful if the exception needs to be re-thrown (re-thrown exceptions are caught by exception handlers further up the call stack)

It should be noted that choosing not to catch an exception is perfectly valid if the intention is for it to be handled at a higher level.

Catching an exception is done by wrapping the potentially-throwing code in a try { ... } block as follows, and catching the exceptions it's able to handle in a catch (ExceptionType) { ... } block:

Console.Write("Please enter a filename: ");
string filename = Console.ReadLine();

Stream fileStream;

try
{
    fileStream = File.Open(filename);
}
catch (FileNotFoundException)
{
    Console.WriteLine("File '{0}' could not be found.", filename);
}

Stats

Contributors: 2
2016-07-22
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook