You've seen several scenarios when errors have occurred when converting types. C# calls this, an exception has been thrown.
Good practice is to avoid writing code that will throw an exception whenever possible, perhaps by performing if
statement checks, but sometimes you can't. In those scenarios, you must catch the exception and handle it.
As you have seen, the default behavior of a console application is to display details about the exception in the output and then stop running the application.
You can take control over how to handle exceptions using the try
statement.
Add a new console application project named HandlingExceptions
.
When you know that a statement can cause an error, you should wrap that statement in a try
block. For example, parsing from a string to a number can cause an error. We do not have to do anything inside the catch
block. When the following code executes, the error will get caught and will not be displayed, and the console application will continue running.
In the Main
method, add the following statements:
WriteLine("Before parsing"); Write("What is your age? "); string input = Console.ReadLine(); try { int age = int.Parse(input); WriteLine($"You are {age} years old."); } catch { } WriteLine("After parsing");
Run the console application and enter a valid age, for example, 43
:
Before parsing
What is your age? 43
You are 43 years old.
After parsing
Run the console application again and enter an invalid age, for example, kermit
;
Before parsing
What is your age? kermit
After parsing
The exception was caught, but it might be useful to see the type of error that occurred.
Modify the catch
statement to look like this:
catch(Exception ex) { WriteLine($"{ex.GetType()} says {ex.Message}"); }
Run the console application and again enter an invalid age, for example, kermit
:
Before parsing
What is your age? kermit
System.FormatException says Input string was not in a correct format.
After parsing
Now that we know which specific type of exception occurred, we can improve our code by catching just that type of exception and customizing the message that we display to the user.
Leave the existing catch
block, but add the following code above it:
catch (FormatException) { WriteLine("The age you entered is not a valid number format."); } catch (Exception ex) { WriteLine($"{ex.GetType()} says {ex.Message}"); }
Run the program and again enter an invalid age, for example, kermit
:
Before parsing
What is your age? kermit
The age you entered is not a valid number format.
After parsing
The reason we want to leave the more general catch
below is that there might be other types of exceptions that can occur. For example, run the program and enter a number that is too big for an integer, for example, 9876543210
:
Before parsing
What is your age? 9876543210
System.OverflowException says Value was either too large or too small for an
Int32.
After parsing
Let's add another catch for this new type of exception:
catch(OverflowException) { WriteLine("Your age is a valid number format but it is either too big or small."); } catch (FormatException) { WriteLine("The age you entered is not a valid number format."); }
Rerun the program one more time and enter a number that is too big:
Before parsing
What is your age? 9876543210
Your age is a valid number format but it is either too big or small.
After parsing
Note
The order in which you catch exceptions is important. The correct order is related to the inheritance hierarchy of the exception types. You will learn about inheritance in Chapter 3, Building Your Own Types with Object-Oriented Programming. However, don't worry too much about this—the compiler will give you build errors if you get exceptions in the wrong order anyway.