Skip to main content

Python Exceptions

Exception is unusable condition and error that can occurred when execute code. This are indicated some wrong in our source code. that means code are syntactically correct. but applied operations is invalid or its results are not valid. let's views some exceptions and their solutions

ValueError Exceptions

Python is support dynamic data type. so this error are occurred probably when user are provides wrong input values at the run time. for example.

#ValueError Example
n = int(raw_input("input integer value : ")) #type 22dd
print(n)

See this example, this is syntactically valid program. when execute program then console are hold the instruction and wait for an integer value. but in this situation programmer are not control which type of value are insert by user. so in this case if user are not provide valid integer. then see this case.

Input : 22dd
input integer value : 12dd
Traceback (most recent call last):
  File "test.py", line 2, in <module>
    n = int(raw_input("input integer value : ")) #type 22dd
ValueError: invalid literal for int() with base 10: '12dd'

This exceptions are destroyed program execution. so there is important to control this error. python are provides solution to handling this type of situations exception handling is technique to resolve this type of errors. let see this solutions.

#Handle ValueError Example
try:
  n = int(raw_input("input integer value : ")) #type 22dd
  #executes instruction when no exception
  print(n)
except ValueError:
  print("Opps invalid input")
Output
input integer value : 22dd
Opps invalid input

try block are used to define statement and expression that are produced an runtime error(exception). If try block are found any error then relevant except block are executed. that are a way to control exceptions.

OverflowError Exception

#OverflowError example
def check(): 
    result = 1
    for k in range(677): 
      result+=(56./(56.*k+1.) - 45./(8.*k+4.))**k**5555 
    return result 
print(check())
Error like this
Traceback (most recent call last):
  File "test.py", line 7, in <module>
    print(check())
  File "test.py", line 5, in check
    result+=(56./(56.*k+1.) - 45./(8.*k+4.))**k**5555 
OverflowError: long int too large to convert to float

control this error like this

#OverflowError example
def check(): 
    result = 1
    for k in range(677): 
      try:
        result+=(56./(56.*k+1.) - 45./(8.*k+4.))**k**5555 
      except OverflowError:
        print("oops exceed the range of result variable"+
          "long int too large to convert to float")
        return
    return result 
print(check()) #None
Output
oops exceed the range of result variablelong int too large to convert to float
None

TypeError Error


result='1'+3 #TypeError
print(result)
Error
Traceback (most recent call last):
  File "test.py", line 1, in <module>
    result='1'+3 #TypeError
TypeError: cannot concatenate 'str' and 'int' objects

Solution of this problems

# solution of TypeError
try:
  result='1'+3 #TypeError
  print(result)
except TypeError:
  print "Invalid Type"
except ValueError:
  print "Invalid Input"
finally:
  #this block is always work . 
  #whether if exception is occurred or not
  #do remainning other task
  print("Finally block")
Output
Invalid Type
Finally block

KeyError

#KeyError Example 
data={"s":"ss","v":"vv"}
data['ss'] #KeyError: 'ss'
Error
Traceback (most recent call last):
  File "test.py", line 3, in <module>
    data['ss'] #KeyError: 'ss'
KeyError: 'ss'

Solution of this problem

#KeyError Example 
try:
  data={"s":"ss","v":"vv"}
  data['ss'] #KeyError: 'ss'
except KeyError:
  print "OOps key not exist"
Output
OOps key not exist

IndexError Exceptions

This error are is occurred when try to access element of undefined.

data="01234"
data[6] #IndexError

KeyboardInterrupt Exceptions

Wrong logic of termination condition can produces infinite execution of looping statement. This situation we are closed the terminal or use other alternative approach to stop our program execution . like as (ctrl+c, or ctrl+z). know that is also an exception.

for in given example that is while loop are no termination condition. so this program are stop by ctrl+c by user programmer.

result=1
while True:
  result+=1
  print(result)
Error
:
:
:
111044
111045
111046
111047
111048
111049
111050
111051
^CTraceback (most recent call last):
  File "test.py", line 4, in <module>
    print(result)
KeyboardInterrupt
close failed in file object destructor:
sys.excepthook is missing
lost sys.stderr

This is keyboard interrupt, in this situation (ctrl+c) are used to stopped the current execution program. that is an exception because program is terminated abnormally. so use of this solution

#KeyboardInterrupt
try :
  result=1
  #infinite execution of loop
  #no break condition
  while True:
    result+=1
    print(result)
except KeyboardInterrupt:
  print("OOps keyword stop execution")
#control + C to terminate program
Output
:
:
:
111044
111045
111046
111047
111048
111049
111050
111051
^COOps keyword stop execution

ZeroDivisionError Exception

result=True/0

#result=1/0
#result=1.0/0
Error
Traceback (most recent call last):
  File "test.py", line 1, in <module>
    result=True/0
ZeroDivisionError: integer division or modulo by zero

IOError Exception

This is an basic error are occurred when open file are not exist in current directory or location.

#IOError when file are not found
fileData=open("mytext.txt")
Error
Traceback (most recent call last):
  File "test.py", line 2, in <module>
    fileData=open("mytext.txt")
IOError: [Errno 2] No such file or directory: 'mytext.txt'

NameError Exception

When object are not exist in given scope that this type of exception are display in console. see example


print(name)
Error
Traceback (most recent call last):
  File "test.py", line 1, in <module>
    print(name)
NameError: name 'name' is not defined

Solution of like this.

try:
  print name
except  NameError:
  print("object are not defined")

Most of cases 70% error are occurred of programer wrong logic. and 30% error can be occurred user interaction and system failure situation. so programer responsibility to write better code to avoid unwanted exceptions in during run time.





Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment