← C# from Scratch Lesson 39 of 39 · 10 XP

Exceptions

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

An error while the program is running is an exception. If nobody catches it, it stops the program:

Unhandled exception. System.FormatException: The input string 'abc' was not in a correct format.

We catch it with try / catch:

try
{
    int n = int.Parse(input);
    Console.WriteLine(100 / n);
}
catch (FormatException)
{
    Console.WriteLine("That's not a number");
}
catch (DivideByZeroException e)
{
    Console.WriteLine("Error: " + e.Message);
}
finally
{
    Console.WriteLine("always runs");   // close a file, release a resource
}

To throw your own — throw:

if (age < 0)
    throw new ArgumentException("Age can't be negative");
  • catch blocks are checked in order — put specific types before the general catch (Exception);
  • don't swallow errors silently (catch { }) — you'll never find out later what broke;
  • if the error is expected (the user typed nonsense), it's easier without exceptions: int.TryParse(s, out int n) returns false.

Task. For each input line of the form a b, print a / b (integer division). If the line contains something that isn't a number, print error: not a number; if b = 0, print error: division by zero. At the end, print done. Use try / catch.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.