How to handle exceptions in python ?

Submitted 3 years, 5 months ago
Ticket #420
Views 401
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:

try:

...................

.......

...your code

..

except:

...to capture errors...

Submitted 3 years, 5 months ago


Verified

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:
try:
    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
    print(e)
except: 
    # this will catch any remaining errors
    print('Other errors')  

You can read more here: (https://www.idkrtm.com/error-handling-in-python-using-with-and-try/)

Submitted 3 years, 5 months ago


Latest Blogs