5/5/25, 5:11 PM try except
Try Except
The try block lets you test a block of code for errors.
The except block lets you handle the error.
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.
These exceptions can be handled using the try statement:
In [4]: print(x)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-4-fc17d851ef81> in <module>
----> 1 print(x)
NameError: name 'x' is not defined
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")
Variable x is not defined
In [7]: try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Hello
Nothing went wrong
file:///C:/Users/Lenovo/Downloads/try except.html 1/2
5/5/25, 5:11 PM try except
In [9]: try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Something went wrong
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")
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")
Exception: Sorry, no numbers below zero
In [12]: x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")
---------------------------------------------------------------------------
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")
TypeError: Only integers are allowed
In [ ]:
file:///C:/Users/Lenovo/Downloads/try except.html 2/2