Python exception message capturing
Exception handling is achieved using the try-except
block in Python. You can capture the error message using the Exception
class as follows:
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:
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:
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:
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:
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:
Digging deeper with sys.exc_info()
For concrete error descriptions, sys.exc_info()
can be used within an exception block:
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:
This strategy promotes code reuse and encapsulates error handling logic across the application.
Was this article helpful?