An exception is an object representing an unusual event during execution. Python raises exceptions automatically for failures such as an invalid list index, and code can raise them explicitly. Raising one interrupts the normal path: Python searches the current call chain for a matching handler. If none is found, the program exits with an error. section 14.2 section 14.2.2
Exceptions keep recovery code near the place that can respond to a failure. A file-writing function, for example, can catch an I/O failure around several calls without making every lower-level function return and check a success status. section 14.1.1 section 14.2.8
Catch the failure you expect
try: number = float("not a number") except ValueError as error: print("Invalid number:", error) else: print("Converted:", number) finally: print("Conversion attempt finished") The matching except block handles float’s conversion failure, so else does not run. The finally block runs whether conversion succeeds or fails. section 14.2.9 section 3.4.7
The main controls are:
- Use raise ExceptionType(args) to create and raise an exception. Its arguments can carry a message or other details. section 14.2.2
- Put normal work in try. Python checks except clauses in order; except SomeType as error gives the handler access to the object. An except clause can also name a tuple of types. section 14.2.3
- Use else for work that follows a successful try block and finally for actions that must run at the end regardless of an exception. section 3.4.7
Define a specific exception
class EmptyInputError(Exception): pass try: value = "" if not value: raise EmptyInputError("A value is required") except EmptyInputError as error: print(error) A custom exception can be raised and caught like a built-in one. Its arguments are available to the handler through error.args. section 14.2.4 section 14.2.10
Exception types form a class hierarchy. Most inherit from Exception; custom types should generally do so too. Catch a specific type when only that failure can be handled: a handler for Exception also catches many unrelated failures, while KeyboardInterrupt sits outside that branch. An unmatched exception continues up the call chain. section 14.2.1 section 14.2.3
def cell_value(string):
try:
return float(string)
except ValueError:
if string == "":
return 0
else:
return None
A cell-value conversion shows an exception serving ordinary evaluation: a failed numeric conversion becomes 0 for an empty cell or None for other invalid input. section 14.2.9
Use exceptions for errors and, when useful, for computations that must abandon an invalid path. Avoid adding handlers merely because a failure is imaginable; handle conditions where a useful response is possible. For file cleanup, a context manager used with with can ensure an action even if an exception occurs. section 14.2.10 section 14.5
























