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.
Table of Contents
- Introduction to errors and exception in Python
- Default exception handler
- Using try/except
- Multiple exceptions
- Custom Exceptions
- Finally clause
- Optional else block
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 = 5print(test_list[index])
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.
Default Exception Handler
Suppose we write the following code:
#default exception handlertest_list = [1, 2, 3]index = 5print(test_list[index])
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.
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 handlertest_list = [1, 2, 3]index = 5print(test_list[index])
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.
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 nameOrexcept (type1, type2, …) as variable_name: (If several except suites are identical)#Handling multiple exceptions multiple except clausestest_list = [1, 2, 3]while True:value = input('Enter the index: ')if value == 'q':breaktry: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)
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 Exceptionsclass LowercaseException(Exception):passtest_words = ['PYTHON', 'java', 'R', 'GO LANG', 'C']for word in test_words:if word.islower():raise LowercaseException(word)
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 Exceptionsclass LowercaseException(Exception):passtest_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)
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 clausetest_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")
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 clausetest_list = [1, 2, 3]index = 2try: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!!")
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.
Download this article as PDF to read offlineDownload as PDF