Exception_handling
Exception_handling
Types of errors
1. Compile time errors
2. Runtime errors
Compile time errors: The errors which occur during the compilation of the
program. These are called syntax errors. If there is syntax error program
execution is not done.
Runtime errors : The errors which occur during the execution of program is
called runtime error. If there is an error during runtime program execution is
terminated.
These runtime errors also called logical errors or exception.
Why runtime errors occur because of wrong input given by enduser.
n1=int(input("enter number"))
print(n1)
enter number45
45
>>>
====================== RESTART:
C:/Users/admin/Desktop/python7am/p307.py ======================
enter numberabc
Traceback (most recent call last):
File "C:/Users/admin/Desktop/python7am/p307.py", line 1, in <module>
n1=int(input("enter number"))
ValueError: invalid literal for int() with base 10: 'abc'
>>>
Types of errors
1. Compile time errors
2. Runtime errors
Compile time errors: The errors which occur during the compilation of the
program. These are called syntax errors. If there is syntax error program
execution is not done.
Runtime errors : The errors which occur during the execution of program is
called runtime error. If there is an error during runtime program execution is
terminated.
These runtime errors also called logical errors or exception.
Why runtime errors occur because of wrong input given by enduser.
n1=int(input("enter number"))
print(n1)
enter number45
45
>>>
====================== RESTART:
C:/Users/admin/Desktop/python7am/p307.py ======================
enter numberabc
Traceback (most recent call last):
File "C:/Users/admin/Desktop/python7am/p307.py", line 1, in <module>
n1=int(input("enter number"))
ValueError: invalid literal for int() with base 10: 'abc'
>>>
The python virtual machine look for error handler within program, if there is
no error handler within program it is given to default error handler provided
pvm, this error handler display error description and terminate execution of
program.
Default error handler provided python virtual machine does not avoid
abnormal termination of program.
1. Try
2. Except
3. Finally
4. Raise
try block
this block contain the code which has to be monitored for error handling or
exception handling. In this block we include statement which raises error
during runtime.
Syntax:
try:
statement-1
statement-2
statement-3
except block
except block is an error handler, if there is error inside try block it is
handled by except block. Try block followed by one or more than one
except block.
Syntax-1: syntax-2:
try: try:
statement-1 statement-1
statement-2 statement-2
statement-3 except error-type:
except error-type: statement-3
statement-4 except error-type:
statement-4
ZeroDivisionError
exception ZeroDivisionError
Raised when the second argument of a division or modulo operation is
zero. The associated value is a string indicating the type of the operands
and the operation.
def main():
n1=int(input("enter first number"))
n2=int(input("enter scond number"))
try:
n3=n1/n2
print("result is ",n3)
except ZeroDivisionError:
print("number cannot divide with zero")
print("continue..")
main()
exception TypeError
exception ValueError
>>> l1=list(range(1,11))
>>> l1
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> l2=list(10)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
l2=list(10)
TypeError: 'int' object is not iterable
>>>
exception IndexError
Raised when a sequence subscript is out of range
exception KeyError
Raised when a mapping (dictionary) key is not found in the set of
existing keys.
exception NameError
Raised when a local or global name is not found. This applies only to
unqualified names. The associated value is an error message that
includes the name that could not be found.
def main():
list1=[100,200,300,400,500,600,700,800,900,1000]
print(list1)
try:
index=int(input("Enter index to read value"))
print(list1[index])
except IndexError:
print("invalid index")
except ValueError:
print("input must be integer")
main()
def main():
course_dictionary={'java':1000,'python':4000,'c':2000}
print(course_dictionary)
try:
cname=input("Enter course name")
fee=course_dictionary[cname]
print(cname,fee)
except KeyError:
print("invalid course name or course not exists")
main()
finally
finally is not error handler. It is block of code executed which is executed
after try block or except block.
Finally block is used to deallocate resource allocated by try block.
Finally block contain the code which is common for try block and except
block.
Syntax-1: Syntax-2: Syntax-3:
try: try: try:
statement-1 statement-1 statement-1
statement-2 statement-2 statement-2
except <error-type>: finally: except <errortype>:
statement-3 statement-3 statement-3
finally: except <errortype>:
statement-4 statement-4
finally:
statement-5
finally
finally is not error handler. It is block of code which is executed after try
block or except block.
Finally block is used to deallocate resources allocated by try block.
Finally block contain the code which is common for try block and except
block.
Syntax-1: Syntax-2: Syntax-3:
try: try: try:
statement-1 statement-1 statement-1
statement-2 statement-2 statement-2
except <error-type>: finally: except <errortype>:
statement-3 statement-3 statement-3
finally: except <errortype>:
statement-4 statement-4
finally:
statement-5
def main():
try:
print("inside try block")
n1=int(input("enter first number"))
n2=int(input("enter second number"))
n3=n1/n2
print(n3)
except ZeroDivisionError:
print("inside except block")
finally:
print("inside finally block")
print("continue...")
main()
raise keyword
raise keyword is used to generate error or exception explicitly.
raise <error-type>
Example
def multiply(x,y):
if x==0 or y==0:
raise ValueError
else:
return x*y
def main():
n1=int(input("enter n1 value"))
n2=int(input("enter n2 value"))
try:
n3=multiply(n1,n2)
print(n3)
except ValueError:
print("cannot multiply number with zero")
main()
Syntax:
class <error-class-name>(Exception):
def __init__(self):
super().__init__()
Example
class ZeroMultiplyError(Exception):
def __init__(self):
super().__init__()
def multiply(n1,n2):
if n1==0 or n2==0:
raise ZeroMultiplyError
else:
return n1*n2
def main():
num1=int(input("enter first number"))
num2=int(input("enter second number"))
try:
num3=multiply(num1,num2)
print(num3)
except ZeroMultiplyError:
print("cannot multiply number with zero")
main()
Example
class InsuffBalError(Exception):
def __init__(self):
super().__init__()
class Account:
def __init__(self,accno,name,bal):
self.__accno=accno
self.__cname=name
self.__balance=bal
def deposit(self,amt):
self.__balance=self.__balance+amt
def withdraw(self,amt):
if self.__balance<amt:
raise InsuffBalError
else:
self.__balance=self.__balance-amt
def print_account(self):
print("AccountNo :",self.__accno)
print("CustomerName :",self.__cname)
print("Balance :",self.__balance)
def main():
acc1=Account(101,"naresh",5000)
acc1.print_account()
acc1.deposit(2000)
acc1.print_account()
try:
acc1.withdraw(3000)
acc1.print_account()
acc1.withdraw(6000)
acc1.print_account()
except InsuffBalError:
print("insuff balance")
main()