What is Exceptional Handling in python

Introduction

In this blog, we would discuss What is Exceptional Handling in python. In Python, exceptions are handled using try-except blocks. When an exception occurs in a try block, the code in the except block is executed. If an exception occurs in the except block, the code in the final block is executed. If an exception occurs in the final block, the exception is propagated to the caller. Exception handling allows us to gracefully handle errors and unexpected conditions in our code. It is a robust and reliable way to handle errors and prevent our code from crashing. There are a variety of built-in exceptions in Python, and we can also create our own custom exceptions. When writing code that could potentially result in an exception, we should first think about what kind of exception could occur and how we want to handle it. This will help us write more robust and reliable code.

 

 

Examples of Exceptional Handling in python

In Python, exceptions can be handled using a try…except block. When an exception occurs, it can be handled by an except clause. If an exception occurs that does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above. A try…except block can handle multiple exceptions. To do this, simply provide a comma-separated list of exceptions as the first argument to the except clause.

import sys

randomList = ['a', 0, 2]

for entry in randomList:
    try:
        print("The entry is", entry)
        r = 1/int(entry)
        break
    except:
        print("Oops!",sys.exc_info()[0],"occurred.")

print("The reciprocal of",entry,"is",r)

Output:

 

 

Python has various built-in exceptions which force your program to abort and display an error message whenever something goes wrong. For example, if you are trying to open a file that doesn’t exist, then Python will throw a FileNotFoundError exception and your program will come to a sudden halt. Similarly, if you are trying to divide a number by zero, then Python will throw a ZeroDivisionError exception. In general, it is a good idea to handle exceptions gracefully instead of letting your program crash. 

try:
 # Some risky code here
except FileNotFoundError:
 print("Sorry, the file you are trying to open doesn't exist!")
except ZeroDivisionError:
 print("Sorry, you can't divide by zero!")

 

In the above example, we have two risky code blocks which can potentially raise exceptions. We have handled these exceptions using try…except blocks. If any of the risky code blocks raises an exception, then the corresponding except block will be executed and the rest of the code will be skipped.

 

It is also possible to catch multiple exceptions in a single except block.

 

try:
 # Some risky code here
except (FileNotFoundError, ZeroDivisionError):
 print("Sorry, something went wrong!")

 

In the above example, we have catch FileNotFoundError and ZeroDivisionError exceptions in a single except block.

 

We can also get more information about the exception by using the keyword.

 

try:
 # Some risky code here
except FileNotFoundError as e:
 print("Sorry, the file you are trying to open doesn't exist!")
 print(e)

In the above example, the exception object is stored in the variable e and we are printing it along with the error message.

 

 

Also, read – What is TypeError and its Solutions?

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *