How should an application group its own errors without also catching signals that are meant to stop it? Derive custom exception classes from Python’s Exception class, not BaseException. BaseException also includes system-exiting exceptions such as KeyboardInterrupt and SystemExit; ordinary errors such as ValueError and NameError fall under Exception. section 12.5.2
Figure 12.6 The common built-in exception classes. The BaseException class is the superclass for all other exception classes. Most exception classes that we interact with are subclasses of the Exception class.
The hierarchy shows where Exception sits below BaseException and above most commonly handled errors. section 12.5.2
An exception is an instance of an exception class. Use raise to produce one, optionally supplying a concise message: raise ValueError("Please use the correct parameter."). Prefer a familiar built-in class when it accurately describes the problem; a wrong argument type, for example, calls for TypeError. section 12.5.1 section 12.5.2
Handle the expected error
A task record with an urgency value of "3#" cannot be converted with int(). Keep the conversion in a small try clause and name the expected error: try: urgency = int("3#") except ValueError as ex: print(f"Couldn't cast the number. Description: {ex}") The message identifies the invalid integer literal. Valid input skips the except clause. Avoid a bare except: name the errors the operation is expected to raise. section 12.3 section 12.3.1 section 12.6
For related application-specific errors, define a package-specific base class that inherits Exception, then derive more specific custom exceptions from it. Use try and except for handling; add else for the no-error path or finally for code that must run whether the operation succeeds or fails. During development, consult Python’s documentation or run suspect code to identify which exception to handle. section 12.6 section 12.4.2 section 12.3.6
























