C# Tutorial - Dissecting Our Fourth Application - Exception HandlingThe .NET Framework provides a standard mechanism for error reporting called structured exception handling. The mechanism relies on exceptions to report an error in the application. Exceptions are classes that provide error information, so therefore you write code in a way that watches for exceptions to be generated by code and then deal with the exceptions in an appropriate manner. There are three components to handling exceptions.
This can be shown in some simple code: try
{
int i = 1/0; // Code to throw exception
}
catch (Exception ex)
{
.. // Code to do something when exception is thrown
}
finally
{
.. // Code to do something every time an exception is thrown
}
Where:
Exception classes are derived from the System.Exception class. Some useful properties are listed here:
Specific ExceptionsWhen an exception occurs in your code, a specific exception is thrown. Once you know the type of exception, then you can cater for it in your code as in App04. ![]() If you enter a non whole number when asked in App03, the dialog above appear and states that a "FormatException was unhandled". This occurred because the Convert class could not convert the entered value, which was a floating point number such as 23.4, into a 32-bit integer. Clicking on View Details action allows more information to be shown about the exception that was thrown. ![]() It is often in this manner when play testing, that most exceptions can be catered for. Hence in the listing for App04, we cater for this exact exception. catch (System.FormatException)
{
. . .
}
|