Python Exception Handling: 5 Tricks You Didn???t Know

Custom Exceptions for Clearer Code
Instead of relying solely on Python’s built-in exceptions, create custom ones for specific scenarios in your application. This makes your code more readable and provides descriptive error messages.

class NegativeNumberError(Exception):
    def __str__(self):
        return "Negative numbers are not allowed!"

def check_positive(number):
    if number < 0:
        raise NegativeNumberError

The Power of the else Clause in Exception Handling
Many (including me before I researched this article) are unaware of the else clause in exception handling. It runs when the try block doesn't raise any exceptions, making your code cleaner.

try:
    result = 10 / 2
except ZeroDivisionError:
    print("Can't divide by zero!")
else:
    print(f"Result is {result}")

Using logging Over print for Exceptions
Instead of using print statements to display exceptions, use the logging module. It's more versatile, allowing you to store error messages in files or other output streams.

import logging

logging.basicConfig(level=logging.ERROR)

try:
    # some code
except Exception as e:
    logging.error(f"An error occurred: {e}")

Catch Multiple Exceptions in One Line
If you have multiple exceptions that need similar handling, catch them in a single line to make your code neater.

try:
    # some code
except (ValueError, TypeError, IndexError) as e:
    print(f"An error occurred: {e}")

Use finally for Cleanup Actions
The finally block runs regardless of whether an exception was raised. It's perfect for cleanup actions, like closing files or releasing resources.

Website