Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson14 / 20

    Module 4 · Reliable programs: copy, handle errors and check results · Lesson 14 of 20

    Handle expected bad input and understand exceptions

    Is a mistyped duration the same kind of failure as an operation throwing an exception? Choose the response that matches the situation.

    An input can be unsuitable even when a program is working correctly. A learner may type a word where you asked for minutes. Use a normal decision for that situation. An operation can also report failure by throwing an exception. That interrupts the current path until a matching handler is found; if none is found, the program can terminate.

    Predict a deliberately handled failure

    This program intentionally calls Parse with text that is not a number so you can follow the exception path. Write the output before running. This is a control-flow demonstration; the next example returns to TryParse for everyday user input.

    C#
    using System;
    
    string text = "oops";
    try
    {
        int minutes = int.Parse(text);
        Console.WriteLine($"Minutes: {minutes}");
    }
    catch (FormatException)
    {
        Console.WriteLine("That text is not a whole number.");
    }
    
    Console.WriteLine("Planner still running.");

    Which two lines print?

    A Minutes: 0; Planner still running.
    B That text is not a whole number.; Planner still running.
    C That text is not a whole number.; Minutes: 0
    D Nothing prints.
    Show answer

    Correct answer: B

    Parse throws a FormatException. The rest of that try block is skipped, the matching catch prints its message, and execution continues after the catch.

    Option A: Parse does not return zero for this invalid format.

    Option C: The Minutes line was skipped when the operation threw.

    Option D: The specific catch handles this demonstrated failure.

    Hint: Follow the path at the failing Parse call.

    Text
    enter try
        |
    int.Parse("oops") --throws FormatException--> matching catch
        |                                           |
    Minutes line is skipped                         v
                                        print useful message
                                                    |
                                                    v
                                      Planner still running.

    Keep a try block close to the operation whose failure you understand. Catch an exception type when you can take a useful next step, such as reporting that a requested operation could not be completed. An empty catch hides the failure and makes later behaviour harder to trust. Catching every Exception and printing success would give the user false information.

    Does catch (FormatException) handle every possible exception?

    A Yes, because every failure has a message.
    B Yes, because it is inside a console program.
    C No, it handles matching FormatException failures.
    D No, catch blocks never handle anything.
    Show answer

    Correct answer: C

    The exception type matters. A failure of another type needs a matching handler or continues out of this block.

    Option A: A message does not make different exception types interchangeable.

    Option B: The kind of application does not broaden the catch type.

    Option D: The first program demonstrates a catch that does handle its matching exception.

    Your turn: validate a daily total

    Two operators help read the decisions: ! reverses a bool, so !int.TryParse(...) is true when parsing fails. || means either condition can be true. It evaluates left to right and skips the right condition if the left is already true. Thus minutes < 0 || minutes > 1440 rejects either side of the allowed range.

    For this small app, the allowed daily total is from 0 through 1440 minutes, inclusive. Ask for text. First reject text that cannot become an int. Then check the permitted range. These are different rules: -1 is a valid int but an invalid daily total for this app. Write the two decisions before comparing your version.

    C#
    using System;
    
    Console.WriteLine("Study minutes:");
    string? text = Console.ReadLine();
    if (!int.TryParse(text, out int minutes))
    {
        Console.WriteLine("Enter a whole number.");
    }
    else if (minutes < 0 || minutes > 1440)
    {
        Console.WriteLine("Use a value from 0 to 1440.");
    }
    else
    {
        Console.WriteLine($"Accepted: {minutes}");
    }

    Enter 25, oops, -1 and 1440 in separate runs. After the prompt, expect respectively Accepted: 25, Enter a whole number., Use a value from 0 to 1440., and Accepted: 1440. An empty line, end of input or an integer outside the int range also causes TryParse to return false. No exception handler is needed for these ordinary validation branches.

    A learner enters -1. Which statement is correct?

    A Parsing succeeds, but the range rule rejects it.
    B Parsing must throw a FormatException.
    C The value is accepted because it is an int.
    D The value becomes 0 automatically.
    Show answer

    Correct answer: A

    -1 is an int value. The second validation step rejects it under the stated application rule.

    Option B: The characters form a valid negative integer.

    Option C: Being representable as an int is different from satisfying this app’s rule.

    Option D: TryParse does not replace a successfully parsed -1 with zero.

    Hint: Separate the representation rule from the product rule.

    Explain it back

    Explain why a validation message is an expected result, and why a catch should not silently claim an operation succeeded. Next lesson uses the same reasoning for files: even a valid path cannot guarantee that a file operation will succeed at the moment it runs.

    References: Microsoft - exception handling and Int32.TryParse.

    Quick reference

    • Use TryParse for expected invalid numeric input.
    • Check application rules after parsing.
    • A throw skips the remaining normal path in that try block.
    • A matching catch can handle a specific failure.
    • Catch only failures you can handle meaningfully.
    • Do not swallow errors or report success after failure.
    Sign in to mark lessons done and keep your place in the course.Sign in

    TechInterviewNotes Editorial Team · Updated 27 Oct 2026 ·