0% found this document useful (0 votes)
31 views12 pages

Exception_handling

Uploaded by

kasifnasim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views12 pages

Exception_handling

Uploaded by

kasifnasim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Exception Handling or Error 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'
>>>

Error handling or exception handling is used to avoid abnormal termination


of program.
When there is an exception or error during runtime program execution is
terminated.
Exception Handling or Error 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'
>>>

Error handling or exception handling is used to avoid abnormal termination


of program.
When there is an exception or error during runtime program execution is
terminated.
Every error is one type or class, creating object of error class and giving to
pvm is called raising exception or error.

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.

Python provide the following keywords to handle errors or exceptions.

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

Raised when an operation or function is applied to an object of


inappropriate type. The associated value is a string giving details about the
type mismatch.

exception ValueError

Raised when an operation or function receives an argument that has the


right type but an inappropriate value.
>>> int("40")
40
>>> int("abc")
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
int("abc")
ValueError: invalid literal for int() with base 10: 'abc'
>>>
# try block with multiple except blocks
def main():
try:
n1=int(input("enter first number"))
n2=int(input("enter second number"))
n3=n1/n2
print(n1,n2,n3)
except ValueError:
print("invalid input or input must be integers")
except ZeroDivisionError:
print("cannot divide number with zero")
main()

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

Custom Errors or user defined error or exception


Exception
All built-in, non-system-exiting exceptions are derived from this class. All
user-defined exceptions should also be derived from this class.

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

You might also like