Skip to content
Lesson 12 of 12

Step 1 of 7 · Reading · ~3 min

Learn

Inheritance, Interfaces, and Exceptions

Exceptions

By the end of this lesson you can catch the errors a program can recover from, run cleanup code no matter what, throw your own exception types, and turn silent integer overflow into a catchable error.

When something goes wrong at run time (dividing by zero, parsing text that is not a number), .NET throws an exception: an object describing the problem. The current method stops at once, and the runtime looks outward through the calling methods for a catch block that handles it. If none does, the program crashes, which the grader reports as a runtime error.

try, catch, finally

static int Withdraw(int balance, string text) {
    int amount = int.Parse(text);                  // may throw FormatException
    if (amount > balance) {
        throw new InvalidOperationException("insufficient funds");
    }
    return balance - amount;
}

try {
    Console.WriteLine(Withdraw(100, "30"));        // 70
    Console.WriteLine(Withdraw(100, "ten"));       // throws; the next line never runs
    Console.WriteLine("unreachable");
}
// the text was not a number:
catch (FormatException) { Console.WriteLine("bad amount"); }
catch (InvalidOperationException ex) { Console.WriteLine("refused: " + ex.Message); }
finally {
    Console.WriteLine("done");                     // runs whether or not anything was thrown
}

This prints 70, bad amount, done. After a catch block finishes, execution continues after the whole try statement. The finally block always runs, so it is the place for cleanup.

  • ex.Message is the text given when the exception was created.
  • Use throw new SomeException("message") to signal a problem you detect yourself.
  • Inside a catch block, a bare throw; rethrows the same exception and keeps its original stack trace. throw ex; resets the trace and is almost always a mistake.

Catch order and the exception family tree

Exceptions form a hierarchy, and a catch matches the named type and everything derived from it. DivideByZeroException and OverflowException both derive from ArithmeticException, which derives from Exception. Catches are tried top to bottom, so list the most specific first:

try { /* ... */ }
catch (DivideByZeroException e1) { /* the specific case */ }
catch (ArithmeticException e2)   { /* any other arithmetic problem */ }
catch (Exception e3)             { /* last resort */ }

Put a general catch above a specific one and the compiler rejects it, because the specific block could never run. Catching plain Exception everywhere hides bugs; catch the types you can actually react to.

Custom exceptions

Define your own type when callers need to tell your error from a built-in one. Inherit from Exception, end the name in Exception, and pass the message to the base constructor:

class OutOfStockException : Exception {
    public OutOfStockException(string item) : base(item + " is out of stock") { }
}

throw new OutOfStockException("pens");    // ex.Message is "pens is out of stock"

Integer overflow is silent unless you ask

Normal int arithmetic wraps around without any error. Wrap an expression in checked(...) to make overflow throw OverflowException instead:

int big = int.MaxValue;
int wrapped = big + 1;                // -2147483648, no error
int safe = checked(big + 1);          // throws OverflowException

int.Parse("99999999999") also throws OverflowException, while int.Parse("abc") throws FormatException. If bad input is expected and common, int.TryParse is cheaper and clearer than catching: reserve exceptions for the unexpected.

Common mistakes

  • General catch before a specific one. Compile error, or, when the types are unrelated, the wrong message.
  • An empty catch { } block. It swallows the error and leaves you debugging silence.
  • throw ex; instead of throw;. The stack trace now points at the rethrow, not at the real problem.
  • Forgetting that + and * on ints wrap. No exception happens unless you use checked.

Your exercise

The starter reads the input lines and has a stubbed Apply method. Complete Apply, define the custom exception, and wrap each line's processing in try/catch so that every problem is reported with the message the exercise lists. The most likely mistakes are catching in the wrong order and forgetting checked, so an overflow prints a wrong number instead of an error.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…