Try Except in Python
Try Except in Python
Try Except
The try block lets you test a block of code for errors.
The else block lets you execute code when there is no error.
The finally block lets you execute code, regardless of the result of the try- and
except blocks.
Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and
generate an error message.
In [4]: print(x)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-4-fc17d851ef81> in <module>
----> 1 print(x)
In [5]: try:
print(x)
except:
print("An exception occurred")
An exception occurred
In [6]: try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
In [7]: try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Hello
Nothing went wrong
In [9]: try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
In [10]: try:
f = open("demofile.txt")
try:
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
except:
print("Something went wrong when opening the file")
In [11]: x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
<ipython-input-11-2edc57024fbc> in <module>
2
3 if x < 0:
----> 4 raise Exception("Sorry, no numbers below zero")
In [12]: x = "hello"
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-12-bc91768a6271> in <module>
2
3 if not type(x) is int:
----> 4 raise TypeError("Only integers are allowed")
In [ ]: