Exception handling in Python

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.

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 
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

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 wihtin finally")
Output
Ronald
 within else 
 I am wihtin 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 ')
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
Visitors Rating
Your Rating




Post your comments , suggestion , error , requirements etc here




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