Experiments with Python - Part 1: Exceptions, Generator and Context Manager

Experiments with Python - Part 1: Exceptions, Generator and Context Manager

Handling Exceptions in Python using Generator and Context Manager

ยท

2 min read

Within 30 minutes of coding with Python, one can experience how easy it is to learn and code in Python. And the more we use it, the more it grows on us. After being working on Python for more than 4 years now, I have started to experiment a bit. The main purpose is to evolve from Pikachu to a Raichu, of course as Python Developer.

I found myself making a lot of REST API calls at work and every time catching exceptions was making my code grow unnecessarily. I can recall I had made REST API calls at more than 10 places and it was too cumbersome to write the exact same exception code again and again. Thankfully, I had generator and context manager to my rescue.

Getting Creative With Exception Handling: The Context Manager and Generator Way

If you have ever worked with file handling in Python, I am sure you would have accessed the file using with context manager. Something like this:

It occurred to me if I create an error handler as a context manager, I could then define it just once and use it everywhere I would like to in my code. This is how I would go about creating an error handling context manager and then use it alongside with:

One downside of this approach is if you loop over an iterable object, the iterator exits out on encountering the exception even though forthcoming objects may not cause the exception. Thereby, your code exits with its complete execution. Solution to this problem is to use continue ๐Ÿ’ก

Here's how you go about it:

Thank you for reading through it. Do let me know if this helped you in way. This is first of the many experiments, that I'll be posting. Consider following if you liked what you read.

ย