How to handle exceptions in python ?

Submitted 3 years, 2 months ago
Ticket #420
Views 349
Language/Framework Python
Priority Medium
Status Closed

While writing code and running it we halt due to some run time errors and exceptions,so

How to handle those exceptions in python and in how many ways we can handle them...

Any answer will be of great help......

Submitted on Apr 27, 21
add a comment

2 Answers

Use try and except methods:




...your code


except: capture errors...

Submitted 3 years, 2 months ago


As Jaanvi is saying, use try .. except.

There are cases where if .. else might work too, but try .. except is a better option, I think.

Let's say you want to devide 2 numbers. In this case you might get ZeroDivisionError.

a = 10
b = 0

# for a / b will generate a ZeroDivisionError on runtime
# to prevent the crash:
    res = a / b
except ZeroDivisionError e:
    # for negative value you will get -inf
    # for positive value you will get inf
    res = a * float('inf')
    # print the error, if you want to see it
    # this will catch any remaining errors
    print('Other errors')  

You can read more here: (

Submitted 3 years, 2 months ago

Latest Blogs