“dynamic error handling” in that our program is
responding to an error when it occurs. To do this we have to use a new C#
construction, the try – catch clause. The try keyword is followed by a block of code.
After the block of code comes the catch clause. If any of the statements following the
try throws an exception the program runs the code in the catch clause to handle this
error.
int age;
try
{
age = int.Parse(ageString);
Console.WriteLine("Thank you");
}
catch
{
Console.WriteLine("Invalid age value");
}
The code above uses Parse to decode the age string. However, the parse action takes
place inside the try block. If the call of Parse throws an exception the code in the
catch block runs and will display a message to the user. Note that once the exception
has been thrown there is no return to the code in the try block, i.e. if the parse fails the
program will not display the message "Thank you".