Skip to content
Exercise · Exceptions · lesson 9 of 9

Exercise: a custom exception

A warehouse has left items in stock, and a customer wants to take n. Complete the two classes in the stub.

  1. OutOfStockException is an exception derived from Exception. Its constructor OutOfStockException(string message) passes the message to Exception, so Message returns exactly that string.
  2. Solution has the method public static int Take(int left, int n). The method returns how many items will remain. If n is greater than left, it throws OutOfStockException with a message like "Only 3 left.", where the number is the value of left.
  • Take(10, 3) → 7
  • Take(5, 5) → 0
  • Take(3, 5) → throws OutOfStockException with the message "Only 3 left."

Constraints: left and n are integers from 0 to 1000; n may be 0.

Do not add extra using directives unless the task says so explicitly.

Solution.cs — csharp
csharp · 15 lines
Ctrl+Enter run · Esc leave editor