Tutorial by Examples

Code can and should throw exceptions in exceptional circumstances. Examples of this include: Attempting to read past the end of a stream Not having necessary permissions to access a file Attempting to perform an invalid operation, such as dividing by zero A timeout occurring when downloading a...
The finally { ... } block of a try-finally or try-catch-finally will always execute, regardless of whether an exception occurred or not (except when a StackOverflowException has been thrown or call has been made to Environment.FailFast()). It can be utilized to free or clean up resources acquired i...
When you want to catch an exception and do something, but you can't continue execution of the current block of code because of the exception, you may want to rethrow the exception to the next exception handler in the call stack. There are good ways and bad ways to do this. private static void AskTh...
Since C# 6.0 exceptions can be filtered using the when operator. This is similar to using a simple if but does not unwind the stack if the condition inside the when is not met. Example try { // ... } catch (Exception e) when (e.InnerException != null) // Any condition can go in here. { ...
Within a catch block the throw keyword can be used on its own, without specifying an exception value, to rethrow the exception which was just caught. Rethrowing an exception allows the original exception to continue up the exception handling chain, preserving its call stack or associated data: try...
Occasionally you'd want to catch an exception and throw it from a different thread or method while preserving the original exception stack. This can be done with ExceptionDispatchInfo: using System.Runtime.ExceptionServices; void Main() { ExceptionDispatchInfo capturedException = null; ...

Page 1 of 1