An exception is defined as an event that occurs application code execution in runtime or build project that is unexpected by the program code.
When we executing our project in in the time different errors can occur in c# code: coding errors made by the programmer, errors due to logical, wrong input, or other unforeseeable things.
C# Exception Classes
All the exception classes in C# are derived from System.Exception class.
Exception | Description |
System.DivideByZeroException | this error has been generated by dividing a number with zero. |
System.NullReferenceException | this error has been generated by referencing the null object. |
System.InvalidCastException | this error has been generated by invalid typecasting. |
System.IO.IOException | handles the Input Output errors. |
System.FieldAccessException | this error has been generated by invalid private or protected field access. |
C# Exception Handling Keywords
- try
- catch
- finally, and
- throw
C# try
The try statement allows you to define a block of code to be tested for errors while it is being executed.
Syntax
try
{
// c# code
}
C# catch
In te c# prorammin languaeg catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
Syntax
catch (Exception e)
{
// Block of code to handle errors
}
C# try and catch
try
{
// c# code to try
} catch (Exception e)
{
// c# code to handle errors
}
C# Finally
The finally statement lets you execute code, after try...catch, regardless of the result:
Syntax
try
{
// c# code in try
}
catch (Exception e)
{
//c# code in Exception
}
finally
{
//c# code finally
}