Using Exceptions in Python
One of good practices in Python is to use exceptions in place of conditions. This practice allows user to get better experience of your application making the application more user-friendly. So let’s learn how we can implement exception handling in Python.
There is a number of built-in exception classes in Python. For instance, if we need a floating point number validation for user input we can use float check and TypeError exception:
try:
float(amount)
except TypeError:
print('Invalid input parameter: Amount should be float')
Exceptions could be useful when working with non-reliable routines like network connections, file system, files etc. For example, when working with Redis server we can handle connection error:
try:
redis_data = self.redis.get(redis_key)
except redis.exceptions.ConnectionError:
print('Redis server is not available')
Sometimes we would like to implement own custom exception classes to handle specific cases. For that, simply create a class extending the base Exception class. Let’s call it CustomError.
Here is an example of handling CustomError exceptions in Flask:
# Create custom exception class
class CustomError(Exception):
"""Input parameter error."""
# Create custom error handler for errors in application
@app.errorhandler(CustomError)
def handle_custom_exception(error):
details = error.args[0]
resp = Response(details['message'], status=200, mimetype='text/plain')
return resp
We create a class CustomError and add an Flask errorhandler for this specific exception passing exception details as arguments in the error object:
details = error.args[0]
Then we can raise the CustomError error somewhere in business logic (for instance, when validate input parameters):
if amount is None:
raise CustomError({ 'message': 'Error: The following arguments are required: amount' })
That’s it. Now having learnt about exceptions handling in Python you are good to go using built-in and creating own custom exceptions. Enjoy Python programming!