Sub topic 3
Your first custom exception
This chapter assumes you can write Python classes, use try, except and raise, and know that a subclass inherits from its parent. You will define one custom exception, see what it inherits, and catch it.
The smallest custom exception
A custom exception is a class that inherits from Exception. The class body can hold only a docstring, because the parent class already supplies the behavior.
class AppError(Exception):
"""Base class for errors raised by this application."""
class ConfigError(AppError):
"""Raised when configuration is missing or invalid."""
try:
raise ConfigError("missing 'database_url'")
except AppError as exc:
print(f"{type(exc).__name__}: {exc}")Running this prints ConfigError: missing 'database_url'.
A docstring is a complete class body, so you don't need pass. ConfigError derives from AppError, so except AppError also catches it. This chapter only introduces that idea. A later chapter covers designing hierarchies.
Inherit from Exception, not BaseException
BaseException is the root of all exceptions. It also covers KeyboardInterrupt, SystemExit and GeneratorExit, which signal that the program or generator should stop. Application errors belong under Exception.
What the subclass inherits
You get the constructor, the message handling and the traceback support without writing any code. The constructor stores every positional argument in the args tuple. str(exc) is built from args.
class AppError(Exception):
"""Base class for errors raised by this application."""
one = AppError("something broke")
print(one.args) # ('something broke',)
print(str(one)) # something broke
two = AppError("something broke", 42)
print(two.args) # ('something broke', 42)
print(str(two)) # ('something broke', 42)With one argument, str() gives that argument as text. With several, it gives the whole tuple, which is rarely what you want to show a user. Pass one clear message for now. A later chapter covers controlling args and __str__.
Raising it and reading the traceback
You raise a custom exception the same way as a built-in one. You can raise the class, and Python creates an instance with no arguments. You can also raise an instance with a message.
def read_setting(settings, key):
if key not in settings:
raise ConfigError(f"missing {key!r}")
return settings[key]
print(read_setting({"debug": "1"}, "debug"))
read_setting({}, "database_url")The first call prints 1. The second call is uncaught and ends the program with a traceback. Its last line reads ConfigError: missing 'database_url'. The class name tells you what category of failure occurred, and the message gives the detail.
Common errors
- Forgetting the parent.
class ConfigError:creates a plain class. Raising it fails withTypeError: exceptions must derive from BaseException. - Writing
passafter a docstring. It does no harm, but it is redundant. - Raising the class instead of a message.
raise ConfigErrorworks, but the traceback shows no detail. Include a message that says what went wrong. - Catching too broadly.
except Exceptionhides bugs unrelated to your error. Catch the narrowest class that fits.
Exercise
You write class ParseError(BaseException): """Bad input.""" and call it from code wrapped in try: ... except Exception:. What happens when the code raises ParseError, and what should you change?
Show answer
The except Exception handler does not catch it, because ParseError is not a subclass of Exception, so the error escapes and can end the program. Change the base class to Exception, or to your application's base error, which itself derives from Exception.
Exercise
Given err = AppError("disk full", 507), what do err.args and str(err) give?
Show answer
err.args is ('disk full', 507). str(err) is "('disk full', 507)", the text of the whole tuple, because there is more than one argument.