Exception handling in Python


Youtube Live session on Tkinter

exception handling in Python
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)
Full code is here: How try except is used in applications

Test on constant & variables

Python error exception list with messages

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.
AssertionErrorWhen a condition goes false while using assert
AttributeErrorWhen Nonexistence method is called
EOFErrorWhen any input function reches end of the file
FloatingPointErrorWhen any floating point opration fails
GeneratorExitWhen close method is of generator is called
ImportErrorWhen import module is not found
IndexErrorWhen element at index is not found
KeyErrorWhen accessed Key is not present in a dictionary
KeyboardInterruptWhen process is interrupted by Keyboard ( Ctrl + C )
MemoryErrorWhen process runs out of memory
NameErrorWhen accessed variable is not found
NotImplementedErrorWhen abstract methods raise this exception
OSErrorWhen Operating system raised error
OverflowErrorWhen result is too large to handle
ReferenceErrorwhen a weak reference proxy, created by the weakref.proxy() function
RuntimeErrorerror that doesn’t fall in any of the other categories
StopIterationWhen next() does not have any element to return
SyntaxErrorWhen syntax error is encountered by the compiler
IndentationErrorWhen there is an Indentation Error
TabErrorWhen inconsistence Indentation exist
SystemErrorInterpreter generates internal error
SystemExitWhen sys.exit() raise the error
TypeErrorWhen When object has wrong data type
UnboundLocalErrorWhen a local variable is referenced before assignment
UnicodeErrorWhen Unicode encoding decoding error occur
UnicodeEncodeErrorWhen can't encode Unicode character
UnicodeDecodeErrorWhen can't decode Unicode character
UnicodeTranslateErrorWhen Unicode error occur during translating.
ValueErrorWhen an argument of incorrect value to use
ZeroDivisionErrorWhen denominator of a division or modulo operation is zero
File Read File Append
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer