try
and then keep another code block under except
to handle in case of error. If the code within try
block generate some error , the code block within except
will be executed. If there is no error then except
part of the code will not be executed.
my_dict={1:'Alex',2:'Ronald'}
try:
print(my_dict[3]) # 3rd element is not there
except :
print (" some error occured ")
Output is here
some error occured
x=5
y=0
try:
print(x/y)
except Exception as e:
print(e)
except:
print('Hi there is an error')
Output ( this message is because of the line print(e) )
division by zero
We can catch some specific error and display appropriate message.
my_dict={1:'Alex',2:'Ronald'}
try:
print(my_dict[3])
except (KeyError):
print (" This is a key error ")
except :
print (" some error occured ")
Output is here
This is a key error
my_dict={1:'Alex',2:'Ronald'}
try:
print(my_dict[3])
except (KeyError):
print (" This is a key error ")
except :
print (" some error occured ")
finally :
print ( " I came out " )
Output is here
This is a key error
I came out
else
will be executed.
my_dict={1:'Alex',2:'Ronald'}
try:
print(my_dict[2])
except (KeyError):
print (" This is a key error ")
except :
print (" some error occured ")
else :
print ( " within else ")
Output is here
Ronald
within else
my_dict={1:'Alex',2:'Ronald'}
try:
print(my_dict[2])
except (KeyError):
print (" This is a key error ")
except :
print (" some error occured ")
else :
print ( " within else ")
finally:
print ( " I am within finally")
Output
Ronald
within else
I am within finally
my_str="Welcome to 45 town "
my_list=my_str.split() # Create a list using split string method
for i in my_list: # iterating through list
try:
r=1/int(i) # Generate error if i is not integer
print("The interger is :",i)
except:
print ("not integer : ",i) # Print only if integer
Output is here
not integer : Welcome
not integer : to
The interger is : 45
not integer : town
x=13
if x >10:
raise Exception ('Value of x is greater than 10 ')
else:
print('Value is fine ')
Output
Value of x is greater than 10
from sqlalchemy.exc import SQLAlchemyError
def my_update(p_id): # receives the p_id on button click to update
try:
data=(p_name.get(),unit.get(),price.get() )
id=my_conn.execute("UPDATE plus2_products SET p_name=%s
,unit=%s,price=%s WHERE p_id=%s",data)
#print(data)
except SQLAlchemyError as e:
error=str(e.__dict__['orig'])
msg_display=error
show_msg(msg_display,'error') # send error message
except tk.TclError as e:
msg_display=e.args[0]
show_msg(msg_display,'error') # send error message
else:
msg_display="Number of records updated: " + str(id.rowcount)
Full code is here: How try except is used in applications AssertionError | When a condition goes false while using assert |
AttributeError | When Nonexistence method is called |
EOFError | When any input function reches end of the file |
FloatingPointError | When any floating point opration fails |
GeneratorExit | When close method is of generator is called |
ImportError | When import module is not found |
IndexError | When element at index is not found |
KeyError | When accessed Key is not present in a dictionary |
KeyboardInterrupt | When process is interrupted by Keyboard ( Ctrl + C ) |
MemoryError | When process runs out of memory |
NameError | When accessed variable is not found |
NotImplementedError | When abstract methods raise this exception |
OSError | When Operating system raised error |
OverflowError | When result is too large to handle |
ReferenceError | when a weak reference proxy, created by the weakref.proxy() function |
RuntimeError | error that doesn’t fall in any of the other categories |
StopIteration | When next() does not have any element to return |
SyntaxError | When syntax error is encountered by the compiler |
IndentationError | When there is an Indentation Error |
TabError | When inconsistence Indentation exist |
SystemError | Interpreter generates internal error |
SystemExit | When sys.exit() raise the error |
TypeError | When When object has wrong data type |
UnboundLocalError | When a local variable is referenced before assignment |
UnicodeError | When Unicode encoding decoding error occur |
UnicodeEncodeError | When can't encode Unicode character |
UnicodeDecodeError | When can't decode Unicode character |
UnicodeTranslateError | When Unicode error occur during translating. |
ValueError | When an argument of incorrect value to use |
ZeroDivisionError | When denominator of a division or modulo operation is zero |
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.