If we can catch an error then we can write code to handle it. An uncaught error will crash our program.
We can keep our code inside a block placed within 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.
Python error handling using try catch else & finally with system Exception message & specific errors
Example with try & except:
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
All types of error
Capturing any type of error and displaying the system returned message
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.
If you are trying to catch any specific error then that code block should be above of generic exception handling block
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
finally
The code block within finally code block is executed in all conditions ( error or no 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:
If there is no error then code block within 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
else with finally
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
Examples of exception handling
We will separate integer part from a string.
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
User generated exception by using raise
In the code below there is nothing wrong with syntax but user can create its own exception by using raise
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
Specific error handling
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)
There are some common errors which usually raised during execution. A built-in known exception list is available in Python. We can use them and handle specific solution based on the type of exception.