Basic try-except Example :
try:
print(x)
except:
print("An exception occurred")
Output :
An exception occurred
Handle Multiple Exceptions :
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Output :
Variable x is not defined
try-except with else :
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Output :
Hello
Nothing went wrong
finally Block Execution :
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Output :
Something went wrong
The 'try except' is finished
Raise Exception for Negative Number :
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
Output :
Exception: Sorry, no numbers below zero
Raise TypeError for Non-Integer :
x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")
Output :
TypeError: Only integers are allowed