User Defined Exception and Logger
User Defined Exception and Logger
1 User-defined Exceptions
By deriving a new class from the default Exception class in Python, we can define our own exception
types.
In the above code, MyCustomError is derived from the built-in Exception class. You can use this
in your code by using the raise statement.
---------------------------------------------------------------------------
MyCustomError Traceback (most recent call last)
Cell In[2], line 1
----> 1 raise MyCustomError("This is a custom error")
try:
input_num = int(input("Enter a age: "))
if input_num < n:
raise WrongAge # calling your custom exception
else:
print("You can work")
except WrongAge:
print("Invalid Age: You are not allowed to work")
1
2 Logging
Logging is a technique for monitoring events that take place when some software is in use.
For the creation, operation, and debugging of software, logging is crucial.
There are very little odds that you would find the source of the issue if your programme fails and
you don’t have any logging records.
Additionally, it will take a lot of time to identify the cause.
""" In the code above, we first import the logging module, then we call the
basicConfig method to configure the logging.
We set the level to DEBUG, which means that all logs of level
DEBUG and above will be tracked."""
logging.basicConfig(level=logging.DEBUG)
2
WARNING: An indication that something unexpected happened, or may happen in the future
(e.g. ‘disk space low’). The software is still working as expected.
ERROR: More serious problem that prevented the software from performing a function.
CRITICAL: A very serious error, indicating that the program itself may be unable to continue
running.
3 Debug
[4]: import logging
logging.basicConfig(level=logging.DEBUG)
add(1, 2)
[4]: 3
4 Info
[5]: import logging
logging.basicConfig(level=logging.INFO)
def login(user):
logging.info('User %s logged in', user)
login('Admin User')
5 Warning
[6]: import logging
logging.basicConfig(level=logging.WARNING)
def MyBalance(amount):
if amount < 40000:
logging.warning('Sorry you have Low balance: %s', amount)
3
MyBalance(10000)
6 Error
[7]: import logging
logging.basicConfig(level=logging.ERROR)
LetUsDivide(4, 0)
7 Critical Errors
[8]: import logging
logging.basicConfig(level=logging.CRITICAL)
def LetUsCheckSystem(sys):
if sys != 'OK':
logging.critical('System failure: %s', sys)
8 Save to a file
[12]: import os
4
# Try writing a test message to the file
with open(full_path, 'w') as f:
f.write('This is a test message')
[13]: import os
print(os.getcwd())
[15]: import os
import logging
# Set up logging
# Get a logger instance (this will fetch the root logger)
logger = logging.getLogger()
def LetUsCheckSystem(sys):
if sys != 'OK':
logging.critical('System failure: %s', sys)
5
CRITICAL:root:System failure: You need to handle the issue now
[ ]: import pdb
print(addition(5, 7))
[ ]: