An Extensive Guide on Exception Handling in Python
|In this Python tutorial, we shall continue the discussion on Exception handling and various function involved in it with some suitable examples.
Before we jump on the topic of how to handle exceptions, we should have a look at the Exceptions, their types, and some basic in-built exceptions.
1. What is Exception Handling in Python?
As discussed in the previous article, Exceptions can be defined as an output event raised to the calling function when there is a runtime error.
In Python, exceptions are raised when the program encounters an error or we can say when something in the program goes wrong.
Whenever these exceptions occur, the Python interpreter terminates the current process and passes it to the calling process until it is handled. If not handled, the program will crash.
And the process of handling the exceptions in a graceful way such that we control the output and the flow of the program even in case of such exceptions is known as exception handling.
We use a combination of try
, except
, else
, and/or finally
blocks to control the flow of the program and handle the exceptions that we will discuss further in detail.
2. How does Try-Except works in Python
In python, we use try
and except
block for catching and handling the exception. The try
block takes the codes inside it as a normal part of its program. Whereas, the except
block takes the codes inside it as a response for exception which has arisen in the above try
clause.
There can be multiple except blocks after a try statement. These except blocks are handled sequentially and the first except block that can handle the error will be executed.
In case of no error, the except block is skipped and is not executed.
We can specify which exceptions an except
clause should catch. If an except block expects Exception
or does not specify any exception then this block will handle all the exceptions. For example
try: # do something pass except: # handle all exceptions pass
A try
clause can have any number of except
clauses to handle different exceptions, however, only one will be executed in case an exception occurs.
We may pass multiple exceptions in one except clause by providing all values as a parenthesized tuple.
Syntax:
except(AError, BError, CError):
Statements
Let’s take an example to understand the working of try-except blocks.
list_1 = [10, 9, 8, 7] try: print("First element in the list is= %d" %(list_1[0]) print("second element in the list is= %d" %(list_1[1]) print("Fourth element in the list is= %d" %(list_1[3]) print("Fifth element in the list is= %d" %(list_1[4]) #Throws error except IndexError: print("Exceeded Out of Limit.")
Output First element in the list is= 10 second element in the list is= 9 Fourth element in the list is= 7 Exceeded Out of Limit.
try : val = 19 if val < 40 : result = val/(val-19) # throws ZeroDivisionError if val >= 15: print("Result is = ", result) # throws NameError except(ZeroDivisionError, NameError): print ("\nError Present but Resolved")
Output Error Present but Resolved
3. Python try with else block
In certain situations, we might want to run a specific logic only if there is no error in the try
block and for such purpose, we use the else
block.
In python, we use else clause on the try-except
block after writing all except clauses. The codes in the else
block will execute only when the try clause does not raise an exception.
#Small example try: print("Greetings for the day.") except: print("We are sorry.") else: print("All good")
Let’s understand it with a real example. In this example, if the calculation results in ZeroDivisionError
then except block handles it otherwise else block executes.
def div(x,y): try: z = ((x+y) / (x-y)) except ZeroDivisionError: print("Infinity") else: print c # Driver code div(1.0, 4.0) div(2.0, 2.0)
Output -1.6666666666666667 Infinity
3. Finally block in Exception handling
In python, we have the finally
keyword which is placed after the try
and except
blocks. finally
block is always executed and it dooes not depend whether the try
block has been executed normally or throws some exception.
Let’s take an example to understand the working.
try: n = 1//0 #zero exception error. print(n) except ZeroDivisionError: print("Not divisible") finally: # block always executed print('Finally block always executed.')
Output Not divisible Finally block always executed.
4. How can we raise Exception?
We can intentionally raise the exceptions to interrupt the normal program flow. To raise an exception in Python we can use raise
keyword.
It must be either an exception class or an exception instance.
Let’s understand with an example, how it works.
try: raise NameError("Successfully Raised") # Raise Error except NameError: print("Something is wrong") raise # Rechecks if the exception was raised
Output Something is wrong Traceback (most recent call last): File "main.py", line 2, in raise NameError("Successfully Raised") # Raise Error NameError: Successfully Raised
try: amount = int(input("Enter amount:")) if(amount > 10000): raise ValueError else: print("Nice amount") except ValueError: print("Amount more than limit")
Output Enter amount:12000 Amount more than limit
5. Conlusion
In this article, we have covered everything about exception handling.
- What is Exception Handling in Python in detail with some examples.
- The working of Try-Except block in Python.
- Else block in Exception handling.
- Finally block in Exception handling.
- And lastly, how to raise Exception in python
Helpful Links
Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.
Also for examples in Python and practice please refer to Python Examples.
Complete code samples are present on Github project.
Recommended Books
An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding
Do not forget to share and Subscribe.
Happy coding!! ?