Road to become a Python Ninja — Handling Exceptions

Road to become a Python Ninja — Handling Exceptions

hackernoon.com hackernoon.com3 years ago in #Dev Love38

Originally published by Vipul Jain on July 7th 2019 Bullet-proofing your Python code Source: Edureka Special cases aren’t special enough to break the rules — The Zen of Python Why we can’t afford to not have Exception Handling in our Python toolbox? Programming and surprises don’t go hand in hand. In case of an error, we don’t want our program/application to disrupt and the terminates abnormally. Instead, we want to sophisticatedly handle these exceptions and do the required actions in case of exception occurs. Errors A python program terminates the moment it encounters an error. It could happen in case of an error(syntactic error — extra bracket, indentation error, etc) or exception. In this article, we will focus on exceptions. What is an Exception? An exception is an error which happens during the execution of a syntactically correct program. Handling Exceptions → try and except We don’t want our program to terminate midway due to an exception. Instead, we want to capture the exception and run an alternative code in case of exception. This can be done with the help of a try-catch block. tryHere we write the code which could potentially throw an exception. except:Here we write the code which we want to run if the code in above try block throws an exception. Let’s look at at it with an example. The program below will throw an exception and terminates midway if we pass a string which cannot be converted in an integer def convert_to_int(s): num = int(s) print(f’Converted to {num}’) return num # Code completes with no exceptionconvert_to_int(’55’)Converted to 55 # Code gives a value errorconvert_to_int(‘AA’) Traceback (most recent call last):File “”, line 1, in File “”, line 3, in convert_to_intValueError: invalid literal for int() with base 10: ‘AA’ Now let’s use a try catch block to capture the above ValueError Exception def convert_to_int(s): try: num = int(s) print(‘Success’) except ValueError: print(‘Failed’) num = -1 return num convert_to_int(‘AA’)Failed-1 Now we have successfully captured the exception. And instead of the program being terminated, we are running the code in except block. Using finally In some cases, we would want to execute a piece of code, no matter if the exception occurred or not — finallygives us that capability. A classic use case would be — imagine we want to read a table from a database. We will place this code in the tryblock as it might throw an exception. In the exceptblock, we will write the code which we want to execute in case of exception. Now irrespective of the fact that exception occurred or not, we still want to close the connection to database — finally block is the perfect place to put that code. # open database connection try: # Fetch data from databaseexcept Exception as e: # print the exception print(e) finally: print(‘Closing database connection’) # close database connection Raising an Exception → raise In some cases, we would explicitly want to throw an exception based on some condition.raise keyword can be used to throw an exception.  » Read More

Like to keep reading?

This article first appeared on hackernoon.com. If you'd like to keep reading, follow the white rabbit.

View Full Article

Leave a Reply