paint-brush
Road to become a Python Ninja — Handling Exceptionsby@jnvipul
896 reads
896 reads

Road to become a Python Ninja — Handling Exceptions

by Vipul JainJuly 7th, 2019
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

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.

Company Mentioned

Mention Thumbnail
featured image - Road to become a Python Ninja — Handling Exceptions
Vipul Jain HackerNoon profile picture

Road to become a Python Ninja — Handling Exceptions

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.


**try**Here 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 exception>>> convert_to_int('55')Converted to 55

# Code gives a value error>>> convert_to_int('AA')

Traceback (most recent call last):File "<stdin>", line 1, in <module>File "<stdin>", 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)

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. This can also be used to throw a custom exception.

>>> occupancy = 105

>>> if occupancy > 100:        raise Exception('Occupancy cannot be greater than 100')

# OutputTraceback (most recent call last):

File "<stdin>", line 2, in <module>Exception: Occupancy cannot be greater than 100

Common exceptions in Python

Let’s take a look at some of the most common exceptions in python and in what conditions they are raised.


**Exception**Base class for all exceptions


**IOError**Raised when the file cannot be opened.


**ImportError**Raised when python cannot find the module


**ValueError**Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value


**KeyboardInterrupt**Raised when the user hits the interrupt key (usually Control-C)


**EOFError**Raised when one of the built-in functions (input() or raw_input()) hits an end-of-file condition (EOF) without reading any data


**RuntimeError**Raised when a generated error does not fall into any category


**TypeError**Raised when a function or operation is applied to an object of incorrect type


**ZeroDivisionError**Raised when a division or modulo by zero takes place for all numeric types

Conclusion

In this article, we have covered exception handling in python. We looked at keywords like try, except, finally, raise. We also looked at some of the common exceptions in python.

  • We can use try block to surround a code which could potentially throw an exception
  • We can use except block to execute code when an exception occurs in the try block
  • finally can be used to execute a piece of code which always runs, with or without exceptions in the previous try block.
  • raise can be used to explicitly throw an exception.

Now we can bullet-proof our python code to handle all those exceptions!

Source: ClipartBarn

Other readings