9/28/2018 - 3:06 PM

C# Exceptions TRY and CATCH

When I pass a problem up to my boss I will hand over a note that describes it. Exceptions work in the same way. An exception is a type of object that contains details Creating Programs Exceptions and Errors of a problem that has occurred. When Parse fails it creates an exception object that describes the bad thing that has just happened (in this case input string not in the correct format). The program above ignores the exception object and just registers to the exception event but we can improve the diagnostics of our program by catching the exception if we wish:

int age;
 age = int.Parse(ageString);
 Console.WriteLine("Thank you");
catch (Exception e)
 // Get the error message out of the exception

The catch now looks like a method call, with the Exception e being a parameter to
the method. This is exactly how it works. Within the catch clause the value of e is set
to the exception that was thrown by Parse. The Exception type has a property called
Message which contains a string describing the error. If a user types in an invalid
string the program above will write the text in the exception, which contains the

Input string was not in a correct format.

This message is obtained from the exception that was thrown. This is useful if the code
inside the try block could throw several different kinds of exception, since it means
that the message reflects what has actually hap