GCSE Link: 2.14 (Errors)
Example 1 shows some example C# code to add 5 to a given number.
Example 1
int num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(num + 5);
This works fine when the user inputs a number like 7, but if the user enters
something like abc, the program will crash:
Unhandled exception. System.FormatException: The input string 'abc' was not in a correct format.
at System.Number.ThrowFormatException[TChar](ReadOnlySpan`1 value)
at System.Convert.ToInt32(String value)
at Program.Main()
Command terminated by signal 6
So, we need to handle this exception. We use the try...catch syntax.
Example 2 shows some example C# code to add 5 to a given number with exception handling.
Example 2
try {
int num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(num + 5);
} catch (Exception e) {
Console.WriteLine("Error: " + e);
// Do anything here
}
Can you think of any other common scenarios where exceptions can occur?
Index out of range when indexing an array; Dividing by zero; Integer overflows