Custom Errors in Python
Our first example demonstrates how to create custom error types in Python. This is similar to implementing the Error()
method in other languages.
from typing import Tuple, Optional
# A custom error type usually has the suffix "Error".
class ArgError(Exception):
def __init__(self, arg: int, message: str):
self.arg = arg
self.message = message
def __str__(self):
return f"{self.arg} - {self.message}"
def f(arg: int) -> Tuple[int, Optional[Exception]]:
if arg == 42:
# Return our custom error.
return -1, ArgError(arg, "can't work with it")
return arg + 3, None
def main():
# In Python, we use isinstance() to check if an exception
# is of a specific type. This is similar to errors.As in other languages.
_, err = f(42)
if isinstance(err, ArgError):
print(err.arg)
print(err.message)
else:
print("err doesn't match ArgError")
if __name__ == "__main__":
main()
To run the program:
$ python custom_errors.py
42
can't work with it
In this example, we define a custom ArgError
class that inherits from the built-in Exception
class. This is equivalent to implementing the error
interface in some other languages.
The f
function returns a tuple containing the result and an optional error. This pattern mimics error handling in languages that have explicit error return values.
In the main
function, we use isinstance()
to check if the returned error matches our custom ArgError
type. This is similar to using errors.As
in some other languages.
Python’s exception handling is typically done using try/except blocks, but this example shows how you can implement a error-return style if needed for compatibility with other systems or languages.