Raising & custom exceptions

Errors & Exceptions, lesson 5 of 6

🛟 Errors & Exceptions, lesson 5 of 6

Raising & custom exceptions

Signal problems with raise, validate input and define your own errors.

12 min

2 exercises

1 quiz

0/3 solved

Getting Python ready… examples can run in a moment.

So far Python raised the errors. You can raise them too, with raise. It's how a function says "I can't work with this input" instead of silently returning a wrong value.

Example

Refuse bad input

Your message appears in the traceback. Change 250 to 100 and the program finishes normally.

Why raise instead of print? A printed warning is easy to miss and the program keeps going with bad data. An exception makes the caller decide: handle it with try/except, or crash loudly.

Pick a fitting type: ValueError for bad values, TypeError for wrong types.

Example

Validate, then handle

One except handles both problems: the one int() raises and the one you raise yourself.

Example

Ask until the input is valid

One line per input() call

The pre-filled input answers "abc", then "42", then "7". Edit the input lines to try other values.

Quiz

What does this print?

Exercise

Validate a username

Make validate_username(name):

  • raise TypeError if name is not a string
  • raise ValueError if it's shorter than 3 or longer than 12 characters
  • raise ValueError if it contains a space
  • otherwise return the name in lowercase

Custom exceptions. You can define your own exception types. Classes come in the next module; for now this two-line recipe is all you need:

class OutOfStockError(Exception):
    pass

It inherits from Exception, so it works with raise and except like any built-in. A clear name documents the problem and lets callers catch exactly your error and nothing else.

Example

A custom exception

Add withdraw(10, 99) on its own line at the end and run it: your custom name appears on the last line of the traceback.

Exercise

Out of stock!

  1. Define a custom exception OutOfStockError.
  2. In buy(stock, item), raise OutOfStockError(item) when the item's count is 0 or the item is missing. Otherwise decrease its count by 1 and return the new count.