Exception Handling In Python

Exception Handling In Python

6 mins read1K Views Comment
Updated on Nov 22, 2022 19:22 IST

In this article, you will learn about errors and exception in Python. You will also gain an understanding on types of exception handling in Python.

2022_03_Exception-Handling-in-Python.jpg

Table of Contents

Introduction to Error and Exception in Python

An error detected during the execution of a program is known as an exception in Python. The exceptions are triggered automatically on errors. However, they can be triggered and intercepted by your code. Handling these errors and exceptions gracefully is essential for writing robust programs. Exceptions are not a new concept. You would have come across them at least once. For example:

 
test_list = [1, 2, 3]
index = 5
print(test_list[index])
Copy code
2022_03_index-exception-1.jpg

This piece of code throws IndexError: list index out of range error. So, when you write a code that might fail under some circumstances, you need appropriate exception handlers to intercept such errors and handle them. In Python programs, we use exceptions for a variety of reasons, such as:

  • Error Handling: Python raises an exception whenever an error occurs during runtime. Python’s default exception-handling kicks in, stopping the program and printing an error message as shown in the above example. You can change the default behavior by defining custom exception handling.
  • Event Notification: You can use an exception in Python to signify an occurrence of an event without having to pass result flags around a program
  • Special-case Handling: At times, in your program, a condition may occur so rarely that it does not make sense to write a code to handle it in multiple places. You can eliminate this special-case code by handling it in exception handlers
  • Termination Actions: Exception handling allows you to specify the set of actions that you would want to be executed when your program terminates
  • Unusual Control Flows: More importantly, exception handling allows you to alter the flow of control of a program

Exceptions are relatively simple tools to work within Python and they revolve around four statements shown below:

  • try/except – Catches and recovers from exceptions raised by Python, or by your code
  • try/finally – Allows to specify termination or cleanup actions, irrespective of exceptions occur or not
  • raise – You can use it to trigger an exception manually in your code
  • assert – You can use it to trigger an exception in your code conditionally

Now that you have enough theoretical knowledge of the concept let’s jump right into some code.

Recommended online courses

Best-suited Python for data science courses for you

Learn Python for data science with these high-rated online courses

Free
4 weeks
12 K
8 hours
4.24 K
6 weeks
40 K
100 hours
4.99 K
– / –
– / –
– / –
– / –
60 hours
– / –
90 hours
1.27 L
12 hours

Default Exception Handler

Suppose we write the following code:

 
#default exception handler
test_list = [1, 2, 3]
index = 5
print(test_list[index])
Copy code

There is not much to this code; it simply tries to print a list element at a given index. Suppose the given index is greater than or equal to the length of the list, an exception will be triggered as Python detects out-of-bounds indexing operation for sequences and reports it by triggering the built-in IndexError exception.

2022_03_default-exception-handler.jpg

You should know that exceptions have a rich type hierarchy. Because we have not explicitly mentioned any code to handle this exception, the default exception handler is invoked and a standard error message is displayed. A typical error message includes the exception that was raised, along with a list of code lines and functions that were active when the exception occurred, which we call stack trace. The default handler also terminates the program immediately.

Catching Exception Using try/except

At times, this might not be what you want, though. You would want your program to be active even after raising the exception. In such cases, you can replace the default behaviour by trying to catch the exception yourself with the help of try/catch block as shown below:

 
#default exception handler
test_list = [1, 2, 3]
index = 5
print(test_list[index])
Copy code

So, what is happening here is that the code in the try block is run. If there is an error, an exception is raised and the piece of code inside the except block is executed. If there are no errors, the except block of code is skipped. In the above example, the generic except block catches all the exceptions. What if your code raises more than one type of exception? In such cases, it is best to provide a separate handler for these exceptions.

Python Sets Practice Programs For Beginners
Python Dictionary Practice Programs For Beginners
Tutorial – for Loop in Python

Catching Multiple Exceptions

You can use any number of specific exception handlers to catch various types of exceptions. If you want exception details beyond just the type, its possible to get the full exception details in the variable name as shown below:

 
except exceptiontype as name
Or
except (type1, type2,) as variable_name: (If several except suites are identical)
#Handling multiple exceptions multiple except clauses
test_list = [1, 2, 3]
while True:
value = input('Enter the index: ')
if value == 'q':
break
try:
index = int(value)
print(test_list[index])
except IndexError as err:
print('Bad index:', 'The index should be between 0 &', len(test_list) - 1, 'but was given', index)
except Exception as othererr:
print('Something else broke:', othererr)
Copy code

The above example first looks for IndexError and it then saves the IndexError exception in the variable err. Any other exception is saved in the variable othererr. If you input 2, IndexError is raised and the input ‘two’ raises some other error, which is handled by our second exception clause.

Raising Custom Exceptions

In all the examples that we have worked on till now, all of the exceptions were predefined in Python or its standard library. However, you can also define your exception types to handle special situations in your code. You can trigger an exception manually using a raise statement. You can handle these exceptions in the same way as Python predefined exceptions.

As you know, the exception is class. So, any custom exception that you create should be a child of class Exception. Let us make a custom exception and raise it when we encounter a lowercase word in a string.

 
#Raising Custom Exceptions
class LowercaseException(Exception):
pass
test_words = ['PYTHON', 'java', 'R', 'GO LANG', 'C']
for word in test_words:
if word.islower():
raise LowercaseException(word)
Copy code

We did not define any behaviour for the LowercaseException, leaving it to the parent class Exception to print the error message. You can access the exception object itself and print as shown below:

 
#Raising Custom Exceptions
class LowercaseException(Exception):
pass
test_words = ['PYTHON', 'java', 'R', 'GO LANG', 'C']
try:
for word in test_words:
if word.islower():
raise LowercaseException(word)
except LowercaseException as exc:
print(exc)
Copy code

Terminating Actions with finally Clause

Sometimes regardless of whether the exception has occurred or not, you want some action to occur. In such cases, you can use the finally clause with try. 

For example, when you are working with files, you have to prevent more than one program from manipulating the same file at once. So, when a program finishes using a file, it should close the file to release it to other programs. Closing the file should be the cleanup action. You can achieve this by using finally.

 
#Demonstrating try/finally clause
test_list = [1, 2, 3]
index = input('Enter the index: ')
try:
print(test_list[index])
except:
print('The index should be between 0 &', len(test_list) - 1, 'but was given', index)
finally:
print("\nFinally Block: This is always executed")
Copy code

Optional Else Blocks

After the last except clause, you can include an optional else clause that has code that will run only if code in the try suite did not raise exceptions.

 
#Demonstrating else clause
test_list = [1, 2, 3]
index = 2
try:
print(test_list[index])
except:
print('The index should be between 0 &', len(test_list) - 1, 'but was given', index)
else:
print("Nothing went wrong!!")
Copy code

Rather than adding an additional code to the try block, it is better to have an else clause because that way, you can avoid accidentally catching an exception that was not raised by the code present in the try block.

Exceptions are a very simple tool and high-level control flow device. Handling exceptions and errors gracefully is an important part of building robust Python programs. It is a good practice to add exception handling anywhere an exception might occur to let the user know what is actually happening.

Top Trending Tech Articles:
Career Opportunities after BTech | Online Python Compiler | What is Coding | Queue Data Structure | Top Programming Language | Trending DevOps Tools | Highest Paid IT Jobs | Most In Demand IT Skills | Networking Interview Questions Features of Java | Basic Linux Commands | Amazon Interview Questions

Recently completed any professional course/certification from the market? Tell us what you liked or disliked in the course for more curated content.

Click here to submit its review with Shiksha Online.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio