Exception handling

try/except

image
image
try:
    f = open("data.txt")
except FileNotFoundError as e:
    print("missing:", e)
else:
    print(f.read())      # runs ONLY if no exception was raised
finally:
    print("cleanup")     # runs ALWAYS — exception or not, return or not
def f():
    try:
        return 1
    finally:
        return 2     # swallows the first return AND any in-flight exception
f()   # 2

Exception types

dir(globals()['__builtins__']) #errors_list — to get the errors list.

  • AssertionError - raised by assert statement
  • AttributeError - Raised when attribute assignment or reference fails
    • AttributeError: 'D' object has no attribute 'f'
    • @property # To make write only variable
      def password(self):
      	raise AttributeError("Password is write-only")
  • IndexError - Raised when the index of a sequence is out of range.
  • KeyError - Raised when a key is not found in a dictionary.
  • NameError - Raised when a variable is not found in local or global scope. NameError: name 'coca' is not defined
  • NotImplementedError - Raised by abstract methods.
  • TypeError - Raised when a function or operation is applied to an object of incorrect type. 334/"44"
  • ValueError - Raised when a function gets an argument of correct type but improper value.
  • def start_tasks_db(db_path, db_type):  # type: (str, str) -> None*
        if not isinstance(db_path, string_types):
            raise TypeError('db_path must be a string')
        ... smth smth smth
        else:
            raise ValueError("db_type must be a 'tiny' or 'mongo'")
  • RuntimeError
  • if self.sock is not None:
        raise RuntimeError('Already connected')
  • ZeroDivisionError
  • FileNotFoundError

Custom exception

class AppError(Exception):
    """Base for everything this package raises."""

class ConfigError(AppError): pass
class RetryableError(AppError): pass

EAFP = easier to ask forgiveness than permission

# LBYL — has a race condition; the file can vanish between check and open
if os.path.exists(path):
    f = open(path)

# EAFP — atomic
try:
    f = open(path)
except FileNotFoundError:
    ...
SuperMade with Super