The C# language’s exception handling features help you deal with any unexpected or exceptional situations that occur when a program is running. Exception handling uses the try, catch, and finally keywords to try actions that may not succeed, to handle failures when you decide that it is reasonable to do so, and to clean up resources afterward. Exceptions can be generated by the common language runtime (CLR), by the .NET Framework or any third-party libraries, or by application code. Exceptions are created by using the throw keyword.
How try-catch operator looks:
try-catch operator in action demo:
try-catch-finally operator in action demo:
try..finally will run your cleanup code and then the exception will keep going, to be handled by something that knows what to do with it.
finally block will be always executed despite exception occured or not.
Let’s create a custom exception class. In order to create an exception handling class, it has to be inherited from System.Exception type, like shown on demo below:
Application that uses this class can be similar to:
Please pay your attention to throw operator.
The throw statement is used to signal the occurrence of an anomalous situation (exception) during the program execution.
C# allows user-defined types to overload operators by defining static member functions using the operator keyword. Not all operators can be overloaded, however, and others have restrictions, as listed by this link
Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
Example below demonstrates how to add additional functionality for int type.