Exception handling is a Python concept used to handle exceptions and errors during program execution. Exceptions can be unexpected, or a developer may anticipate some disruption in the code flow due to an exception that may occur in a specific scenario. In either case, it must be addressed.
Exceptions are caught and handled in Python using try and except code blocks. The code that can raise an exception is enclosed in the try clause, while the code lines that handle the exception are contained in the except clause.
The basic syntax is as follows:
try:
# Some Code
except:
# Executed if we get an error in the try block
# Handle exception here
Example:
# initialize the amount variable
marks = 10000
# perform division with 0
a = marks / 0
print(a)
Here we will get an exception as output.
Output:
Traceback (most recent call last):
File "<string>", line 6, in <module>
ZeroDivisionError: division by zero
Same example using try-except block.
# initialize the amount variable
marks = 10000
try:
a = marks / 0
print(a)
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
Output:
ZeroDivisionError Occurred and Handled
Several approaches can be taken. We can either have multiple except blocks, each dealing with a different exception class, or we can handle multiple exception classes in a single except block.
Example:
# try block
try:
num = int(input("Enter numerator number: "))
denom= int(input("Enter denominator number: "))
print("Result of Division: " + str(num/denom))
# except block handling division by zero
except(ZeroDivisionError):
print("You have divided a number by zero, which is not allowed.")
# except block handling wrong value type
except(ValueError):
print("You must enter integer value")
Output:
Enter numerator number: 23
Enter denominator number: 0
You have divided a number by zero, which is not allowed.
Enter numerator number: yu
You must enter integer value
Here, we are detecting a Particular Exception. A try statement can have multiple except clauses to specify handlers for various exceptions. Please keep in mind that only one handler will be executed.
Note: also read about Errors and Built-in Exceptions
Please follow me to read my latest post on programming and technology if you like my post.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
You are given a stream of elements that is too large to fit into memory.…
The formula for the area of a circle is given by πr². Use the Monte…
Given an integer k and a string s, write a function to determine the length…
There is a staircase with N steps, and you can ascend either 1 step or…
Build an autocomplete system that, given a query string s and a set of possible…
Design a job scheduler that accepts a function f and an integer n. The scheduler…