What is Python Exception Handling?
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.
Try and Except Statement – Catching Exceptions:
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
Catching Multiple Exceptions :
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
Follow Me
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.
Leave a Comment