Showing posts with label Exceptions. Show all posts
Showing posts with label Exceptions. Show all posts

Exceptional handling for Zero Division Error

# if value of x is given as zero the zero divison error generates and program terminates
x=int(raw_input('Enter the number of students failed:'))
y=100/x
print y


# If x is not defined itself the program not terminated instead it goes to except loop
try:
    x=int(raw_input('Enter the number of students failed:'))
    y=100/x
    print y
except ZeroDivisionError:
    x=1
    y=100/x
    print y

Exceptional handling for Name Error

# If x is not defined itself the program not terminated
try:
    y=50*x
except NameError:
    x=1
    y=50*x
    print y
   

Exceptional handling for Key Error

#Without Exceptional handling program terminates if key b not found
s={'d':2,'k':4}
if b in s.keys():
    s['b'].append[9]
else:
    s['b']= 8


#Exceptional handling for key error and program run without termination
s={'d':2,'k':4}
try:
    s['b'].append[9]
except KeyError:
    s['b']= 8

To use try except for error handling

try:
      s=0
      g=s/0   # Division by zero creates error
      print 'Value of g :',g

except:
      print 'Something went wrong.'



try:
      s=0
      g=s/10   # Division by zero by 10  creates no error
      print 'Value of g :',g

except:
      print 'Something went wrong.'