Python Exception Handling

wahyu eko hadi saputro
2 min readJan 18, 2022

--

Ok now i will discuss about exception handling in python. The first question is “what is exception handling ?”. Exception is anomaly or unexpected condition like we expect sunny day but suddenly the rain is coming. Sunny is expectation and rain is exception. And handling is how to handle unexpected condition like we bring umbrella to handle / overcome if rain coming. So exception handling is how we handle / tackle every exception on a running application.

Actually every programming language has style / build in feature how to handle exception. And in python here is the schema / structure of python class to handle exception

Programming In Python 3 Second Edition page 172

Python is following OOP concept, the highest parent class is always object class. The derived classes from object class is called child class. Based on picture the BaseException class is parent class of Exception class and BaseException class also child class of object class. Python does not have private modifier, so that every child class will inherit every method and variable from parent class.

We can create our custom exception based on our need. Below is example of custom exception :

import logging
import warnings
_logger = logging.getLogger(__name__)""" it is custom exception """
class BusinessException(Exception):
"""
it is constructor of custom exception
:param code: code of message exception
:param message: exception message and frontend modal content
"""
def __init__(self, code, message):
super().__init__(message)
self.code = code
self.message = message
def get_message(self):
return self.message
def get_code(self):
return self.code

Class BusinessException extends functionality of Exception parent class.

How to use BusinessException, here is example of code how to use BusinessException:

import logging
import warnings
_logger = logging.getLogger(__name__)
from exception_util.custom_exception import BusinessException
def exception_test(param):
if param == 1:
raise BusinessException("123","custom error exception")
if param == 2:
raise Exception("exception")
def main():
print("start")
try:
exception_test(1)
except BusinessException as customErr:
_logger.error(customErr.get_message())
except Exception as customErr:
_logger.error(customErr)
finally:
print("finally")
if __name__ == "__main__":
main()

usually python has 3 block to handle exception :

try:except:finally:

Try block is mandatory. you can make many combination among try, except and finally like try and finally only, try and except only, etc. for more information please read python documentation or book : Programming In Python 3 Second Edition page 172

github : https://github.com/wahyueko22/belajar_python/tree/master/exception_handling

Source :

Programming In Python 3 Second Edition

--

--

No responses yet