15
loading...
This website collects cookies to deliver better user experience
try
statement is used to prevent errors while coding. You might try to pop from an empty list, process user input character as an int or divide by zero, this statement has got you covered!.try:
#statement1- try to execute, but if any error is returned, then do not execute
except:
#statement2- execute if any error occurs
finally: #optional
#Statement2- execute nevertheless
try
& except
statements provide a robust alternative for the if-else statement. But this comes at the cost of a little more difficulty while debugging, when unexpected errors are not displayed. This is somewhat similar too the throw
catch
statements in C.a=input("Please enter a number ")
try:
b=int(a)
print(b)
except:
print("OOPS! You entered a non-numeric character! ")
finally:
print("End of program!")
Please enter a number 6
6
End of program!
Please enter a number g
OOPS! You entered a non-numeric character!
End of program!
>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
try:
print(x)
except ZeroDivisionError:
print("Cannot divide by zero.")
except:
print("Something else went wrong")
pass
statement comes into play. The pass
statement is basically a 'no-operation' statement in Python.try:
#try to execute
except:
pass
#do nothing