Explain Codes LogoExplain Codes Logo

Python exception message capturing

python
exception-handling
logging
ftp-operations
Nikita BarsukovbyNikita Barsukov·Dec 2, 2024
TLDR

Exception handling is achieved using the try-except block in Python. You can capture the error message using the Exception class as follows:

try: # Risky operation - hold tight! risky_call() except Exception as e: # Catch the error message and print, or log print(f"Hey there! This went wrong: {e}")

This code snippet tragets errors originating from the function risky_call(), and prints or logs the exceptions.

Detailed exception handling and logging

Syntax differences across Python versions

The syntax for handling exceptions varies across different versions:

  • In Python 2.x, use except Exception, e:
  • In Python 3.x, you would use except Exception as e:

Always ensure that you use the correct syntax relevant to your Python version to avoid basic syntax errors.

Exception logging with logging module

Rather than merely printing the exception message, you can log it to a file or a stream - it serves as a handy tool for debugging issues in production:

import logging logger = logging.getLogger(__name__) logging.basicConfig(level=logging.ERROR, filename='app.log') try: # FTP upload operation perform_ftp_upload() except Exception as e: # Because print statements in code are so 2012! logger.error(f"It broke! Here's why: {e}", exc_info=True)

The exc_info=True in the logger.error() function, prints out the complete traceback in the log -- this gives a better context about where and why the exception occurred.

Handling FTP operations

Working with FTP operations, we can use the ftplib or urllib libraries. FTP address and file path can be defined as global variables for easy modification when required:

FTP_ADDRESS = 'ftp.example.com' # Change me, maybe? FILE_PATH = '/path/to/your/file' # No, not that path.. the other path! # FTP function using ftplib or urllib def perform_ftp_upload(): from ftplib import FTP ftp = FTP(FTP_ADDRESS) # ftp operations...

This approach allows for simple and easy access to the FTP address and file path whenever changes are required.

Ensuring file safety with with statement

When dealing with files, the with statement can be used to ensure that files are properly closed after operations are carried out:

with open('cloud_flat_file.csv', 'rb') as file: ftp.storbinary('STOR cloud_flat_file.csv', file)

Moral of story: "Use with, and file will play safe!"

Advanced exception handling strategies

Catch 'Em All with BaseException

If you're looking to capture all types of exceptions, including system-exiting ones, you can use the base BaseException class:

try: operation_that_might_quit() except BaseException as e: logger.error("System Exited. Don't panic! Here's why:", exc_info=True)

Use it with caution though, as it may catch interruptions like Ctrl+C that are intended to stop the program.

Converting exception messages for logging

If you just need the plain exception error message as a string, you can convert it using str(e). Comes handy while logging exceptions:

except Exception as e: logger.error(str(e))

Digging deeper with sys.exc_info()

For concrete error descriptions, sys.exc_info() can be used within an exception block:

import sys except Exception: error_type, error_value, traceback = sys.exc_info() logger.error(f"Friendly alert! Type of error: {error_type}, Its value: {error_value}") logger.debug("Details for nerds:", exc_info=True)

This leads us to capture the types of errors, their values and the traceback for a more granular and detailed log output.

Dedicated exception handling function

Seize the chance to keep your code clean and drift away from clutter, by creating a dedicated function to handle exception logging:

def handle_exception(e): logger.error("An unknown entity caused an exception", exc_info=True) # Add custom error handling ... # Integrated in the main code as follows: except Exception as e: handle_exception(e)

This strategy promotes code reuse and encapsulates error handling logic across the application.