Recover in C#
C# provides a mechanism to recover from exceptions using `try-catch` blocks. This allows you to handle exceptions gracefully and prevent your program from crashing unexpectedly.
An example of where this can be useful: a server wouldn't want to crash if one of the client connections exhibits a critical error. Instead, the server would want to catch the exception, close that connection, and continue serving other clients.
```csharp
using System;
class Program
{
// This method throws an exception
static void MayThrow()
{
throw new Exception("a problem");
}
static void Main()
{
try
{
MayThrow();
}
catch (Exception e)
{
// The catch block is where we "recover" from the exception
Console.WriteLine("Recovered. Error:\n " + e.Message);
}
// This code will run, because the exception was caught
Console.WriteLine("After MayThrow()");
}
}
In C#, exceptions are caught using try-catch
blocks. The try
block contains the code that might throw an exception, and the catch
block handles the exception if one occurs.
The return value of the catch
block is the exception that was thrown.
When you run this program, you’ll see:
$ dotnet run
Recovered. Error:
a problem
After MayThrow()
Note that unlike in some other languages, in C# you don’t need to explicitly call a “recover” function. The act of catching an exception in a catch
block is effectively the same as recovering from it.
Also, in C#, you can have multiple catch
blocks to handle different types of exceptions differently, and you can use a finally
block to execute code regardless of whether an exception was thrown or not.