C Sharp Exception Handling

C# Exception Handling

To handle runtime errors, the process of Exception Handling is used in C#. Even after the runtime errors, the normal flow of the application can be maintained using the exception handling. Exceptions in C# are events or objects thrown at runtime and are derived from the System.Exception class. It can be handled, else it terminates the program after printing an exception message.

Advantage:

The normal flow of the application is maintained and thus the rest of the code is executed event after the exception.

C# Exception Classes:

In C#, the exception classes are derived from the System.Exception class. The C# common exception classes are listed below.

Exception Uses
System.DivideByZeroException Used to handle the error generated by dividing a number with zero.
System.NullReferenceException Used to handle the error generated by referencing the null object.
System.InvalidCastException Used to handle the error generated by invalid typecasting.
System.IO.IOException Used to handle the Input Output errors.
System.FieldAccessException Used to handle the error generated by invalid private or protected field access.

C# Exception Handling Keywords:

To perform exception handling, the following keywords are used in C#:

  • try
  • catch
  • finally
  • throw