.NET Framework Exceptions Catching an exception

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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);
}


Got any .NET Framework Question?