Python - Handling Exceptions

From: LinkedIn course ‘Python Essential Training’ by Ryan Mitchell https://www.linkedin.com/learning/python-essential-training-14898805

Try, except, finally


import time as time

def causeError():
    start = time.time() #set start timer
    try: 
        #delay run by 0.5 secs
        time.sleep(0.5)
        return 1/0
    except Exception:
        print('There was some sort of error!')
    finally:
        print(f'Function took {time.time() - start} seconds to execute')
        
causeError()
## There was some sort of error!
## Function took 0.5048558712005615 seconds to execute

Custom Decorators *args **kwargs are multiple arguments or string arguments.

def handleException(func):
    def wrapper(*args):
        try:
            func(*args)
        except TypeError:
            print('There was a type error!')
        except ZeroDivisionError:
            print('There was a zero division error!')
        except Exception:
            print('There was some sort of error!')
    return wrapper

@handleException
def causeError():
    return 1/0

causeError()
## There was a zero division error!

Raising exceptions

@handleException
def raiseError(n):
    if n == 0:
        raise Exception()
    print(n)
    
raiseError(0)
## There was some sort of error!
raiseError(1)
## 1

Adding attributes to custom exceptions


class HttpException(Exception):
    statusCode = None
    message = None
    # inherit parent class but with alteration.
    def __init__(self, message=''):
        #super().__init__(colored(message,'red')) #missing package for 'colored' function
        super().__init__(f'Status code: {self.statusCode} and message is: {self.message}')

class NotFound(HttpException):
    statusCode = 404
    message = 'Resource not found'

class ServerError(HttpException):
    statusCode = 500
    message = 'The server messed up'

def raiseServerError():
    raise ServerError()

#raiseServerError()
Python 

See also