Python Exception Handling
Python Exception Handling
We have explored basic python till now from Set 1 to 4 (Set 1 | Set 2 | Set 3 | Set 4).
In this article, we will discuss how to handle exceptions in Python using try, except,
and finally statements with the help of proper examples.
Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are
problems in a program due to which the program will stop the execution. On the
other hand, exceptions are raised when some internal events occur which change the
normal flow of the program.
In Python, there are several built-in Python exceptions that can be raised when an
error occurs during the execution of a program. Here are some of the most common
types of exceptions in Python:
These are just a few examples of the many types of exceptions that can occur in
Python. It’s important to handle exceptions properly in your code using try-except
blocks or other error-handling techniques, in order to gracefully handle errors and
prevent the program from crashing.
Example:
There is a syntax error in the code . The ‘if' statement should be followed by a colon
( :), and the ‘print' statement should be indented to be inside the ‘if' block.
Python
amount = 10000
if(amount > 2999)
print("You are eligible to purchase Dsa Self Paced")
Output:
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Except ions: Exceptions are raised when the program is syntactically correct, but the
code results in an error. This error does not stop the execution of the program,
however, it changes the normal flow of the program.
Example:
Here in this code as we are dividing the ‘marks’ by zero so a error will occur known as
‘ZeroDivisionError ’. ‘ZeroDivisionError ’ occurs when we try to divide any number by
0.
Python
marks = 10000
a = marks / 0
print(a)
Output:
In the above example raised the ZeroDivisionError as we are trying to divide a number
by 0.
Note: Exception is the base class for all the exceptions in Python. You can check the
exception hierarchy here.
Example:
output:
Traceback (most recent call last):
File "7edfa469-9a3c-4e4d-98f3-5544e60bff4e.py", line 4, in <module>
z = x + y
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Python
x = 5
y = "hello"
try:
z = x + y
except TypeError:
print("Error: cannot add an int and a str")
Output
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
except:
print ("An error occurred")
Output
Second element = 2
An error occurred
In the above example, the statements that can cause the error are placed inside the
try statement (second print statement in our case). The second print statement tries
to access the fourth element of the list which is not there and this throws an
exception. This exception is then caught by the except statement.
try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)
We use cookies
Example: to ensure
Catching you haveexceptions
specific the best browsing experience
in the Pythonon our website. By using our site, you
acknowledge that you have read and understood our Cookie Policy & Privacy Policy
The code defines a function ‘fun(a)' that calculates b based on the input a. If a is less
than 4, it attempts a division by zero, causing a ‘ZeroDivisionError'. The code calls
fun(3) and fun(5) inside a try-except block. It handles the ZeroDivisionError for
fun(3) and prints “ ZeroDivisionError Occurred and Handled.” The ‘ NameError' block
is not executed since there are no ‘NameError' exceptions in the code.
Python
def fun(a):
if a < 4:
b = a/(a-3)
print("Value of b = ", b)
try:
fun(3)
fun(5)
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")
Output
The output above is so because as soon as python tries to access the value of b,
NameError occurs.
Python
Output:
-5.0
a/b result in 0
Syntax:
try:
# Some Code....
except:
# optional block
We use# cookies
Handling of you
to ensure exception (if
have the best required)
browsing experience on our website. By using our site, you
else: acknowledge that you have read and understood our Cookie Policy & Privacy Policy
# execute if no exception
finally:
# Some code .....(always executed)
Example:
Python
try:
k = 5//0
print(k)
except ZeroDivisionError:
print("Can't divide by zero")
finally:
print('This is always executed')
Output:
Raising Exception
The raise statement allows the programmer to force a specific exception to occur. The
sole argument in raise indicates the exception to be raised. This must be either an
exception instance or an exception class (a class that derives from Exception).
This code intentionally raises a NameError with the message “ Hi t here” using the
raise statement within a try block. Then, it catches the NameError exception, prints
“An except ion,” and re-raises the same exception using raise. This demonstrates
how exceptions can be raised and handled in Python, allowing for custom error
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
messages and further exception propagation.
acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Python
try:
raise NameError("Hi there")
except NameError:
print ("An exception")
raise
The output of the above code will simply line printed as “An exception” but a
Runtime error will also occur in the last due to the raise statement in the last line. So,
the output on your command line will look like
Per formance overhead: Exception handling can be slower than using conditional
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
statements to check for errors, as the interpreter has to perform additional work to
acknowledge that you have read and understood our Cookie Policy & Privacy Policy
catch and handle the exception.
Increased code complexity: Exception handling can make your code more
complex, especially if you have to handle multiple types of exceptions or
implement complex error handling logic.
Possible security risks: Improperly handled exceptions can potentially reveal
sensitive information or create security vulnerabilities in your code, so it’s
important to handle exceptions carefully and avoid exposing too much
information about your program.
Overall, the benefits of exception handling in Python outweigh the drawbacks, but
it’s important to use it judiciously and carefully in order to maintain code quality and
program reliability.
Looking to dive into the world of programming or sharpen your Python skills? Our
Master Pyt hon: Complete Beginner to Advanced Course is your ultimate guide to
becoming proficient in Python. This course covers everything you need to build a
solid foundation from fundamental programming concepts to advanced techniques.
With hands-on projects, real-world examples, and expert guidance, you'll gain the
confidence to tackle complex coding challenges. Whether you're starting from
scratch or aiming to enhance your skills, this course is the perfect fit. Enroll now and
master Python, the language of the future!
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our Cookie Policy & Privacy Policy
N Nikhil Kumar Singh 237