Skip to main content

1. Custom Exception Classes

Python allows you to create your own exception classes by inheriting from the built-in Exception class. Custom exceptions make error messages more meaningful and help handle application-specific errors.

Syntax

Example

Output

Example with Exception Handling

Output

2. Raising vs Catching Exceptions

Raising Exceptions

Raising an exception means deliberately generating an error when an invalid condition occurs. The raise keyword is used for this purpose.

Example

Output

Catching Exceptions

Catching an exception means handling the error using a try and except block so that the program continues running.

Example

Output

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

Output

Logging Levels

Example

Output

Logging to a File

You can store log messages in a file instead of displaying them on the console.

Example

Contents of app.log

Best Practices

  • Create custom exceptions for application-specific errors.
  • Use raise to report invalid conditions.
  • Use try and except to handle exceptions gracefully.
  • Prefer the logging module over print() for debugging and application monitoring.
  • Use appropriate logging levels (DEBUG, INFO, WARNING, ERROR, CRITICAL) based on the importance of the message.

Quick Revision Table