1. Custom Exception Classes
Python allows you to create your own exception classes by inheriting from the built-inException class. Custom exceptions make error messages more meaningful and help handle application-specific errors.
Syntax
Example
Example with Exception Handling
2. Raising vs Catching Exceptions
Raising Exceptions
Raising an exception means deliberately generating an error when an invalid condition occurs. Theraise keyword is used for this purpose.
Example
Catching Exceptions
Catching an exception means handling the error using atry and except block so that the program continues running.
Example
Difference Between Raising and Catching
3. Basic Logging with the logging Module
The logging module is used to record events that happen while a program runs. It is more flexible than using print() statements and is commonly used for debugging and monitoring applications.
Basic Logging Example
Logging Levels
Example
Logging to a File
You can store log messages in a file instead of displaying them on the console.Example
app.log
Best Practices
- Create custom exceptions for application-specific errors.
- Use
raiseto report invalid conditions. - Use
tryandexceptto handle exceptions gracefully. - Prefer the
loggingmodule overprint()for debugging and application monitoring. - Use appropriate logging levels (
DEBUG,INFO,WARNING,ERROR,CRITICAL) based on the importance of the message.