Exception Handling in Python
A system to trap the runtime error when the program is in execution.
Use try and except keywords to trap some runtime error
Python provides a built-in class Exception to trap the error message
Use raise keyword to send some error message using the Exception class
Example 1
def factorial(n):
if(n<0):
raise Exception("Sorry! Number must be >=0")
f=1
i=1
while i<=n:
f=f*i
i=i+1
return f
try:
n=int(input("Enter a number : "))
print("Factorial of",n,"is",factorial(n))
except Exception as e:
print("Error : ",e)
Example 2: Custom Exception
class InvalidNumberException(Exception):
def __init__(self,message):
self.message=message
def __str__(self):
return self.message
def factorial(n):
if(n<0):
raise InvalidNumberException("Sorry! Number must be >=0")
f=1
i=1
while i<=n:
f=f*i
i=i+1
return f
try:
n=int(input("Enter a number : "))
print("Factorial of",n,"is",factorial(n))
except InvalidNumberException as e:
print("Error : ",e)
except ValueError as e:
print("Please provide some number")
Example 3
class Customer:
def __init__(self,cid,name,opamount):
if(opamount)<1:
raise Exception("Sorry! Invalid Amount to open the account")
self.cid=cid
self.name=name
self.balance=opamount
def setName(self,name):
self.name=name
def getCid(self):
if not self.cid.isdigit():
raise Exception("Invalid Customer ID")
return self.cid
def getName(self):
return self.name
def getBalance(self):
return self.balance
def deposit(self,amount):
if(amount<1):
raise Exception("Sorry! Invalid amount to deposit")
self.balance=self.balance+amount
def withdraw(self,amount):
if(amount>self.balance):
raise Exception("Sorry! Insufficient balance")
self.balance=self.balance-amount
try:
cid=int(input('Customer ID'))
name=input('Customer Name')
balance=float(input('Opening Amount'))
c=Customer(cid,name,balance)
amount=float(input('Add amount'))
c.deposit(amount)
amount=float(input('Withdarw amount'))
c.withdraw(amount)
print("Balance of",c.getName(),"is",c.getBalance())
except ValueError as e:
print("Invalid customer id")
except Exception as e:
print("Error ",e)
Comments
Post a Comment