Advertisement
import sys
#Defining our exception class named MyException, inheriting from Exception class
class MyException(Exception):
pass
try :
raise MyException('User-Defined Exception')
except MyException as e :
print("Exception caught : ", e)
#Calling exc_info() function gives the name of caught exception
print("More information about exception : ", sys.exc_info())
Exception caught : User-Defined Exception
More information about exception : (<class '__main__.MyException'>, MyException('User-Defined Exception'), <traceback object at 0x0000000002EF8308>)
import sys
#Defining our exception class named MyException2, inheriting from NameError class
class MyException2(NameError):
pass
try :
raise MyException2('Another User-Defined Exception')
except MyException2 as e :
print("Exception caught : ", e)
#Calling exc_info() function gives the name of caught exception
print("More information about exception : ", sys.exc_info())
Exception caught : Another User-Defined Exception
More information about exception : (<class '__main__.MyException2'>, MyException('User-Defined Exception'), <traceback object at 0x0000000002EF8308>)
Advertisement
#Python - A User Defined Exception Example
class myException2(Exception):
acc_bal = 0 #current account balance
def withdraw(self, debitMoney):
if(self.acc_bal>1000): #if account balance is greater than 1000$ then you can dedit money
acc_bal = acc_bal - debitMoney
else: # if account balance is less than 1000$ then debiting throws our user defined exception.
raise myException2('Cannot debit. Low Account Balance')
ob= myException2()
try:
ob.withdraw(100)
except myException2 as e :
print('Exception handled - ', e)
Exception handled - Cannot debit. Low Account Balance
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement