Exception Handling Example-2
Lesson 14 of 16 in Coddy's Exception Handling in Python course.
Example 1:
Let's take an example of bank transactions. We are having multiple custom exceptions.
1) Assume, user's bank account must contain at least 100$. While transaction, if remaining balance goes below 100$, an Exception should be generated.
2) User should do maximum 3 attempts. If user tries for fourth attempt, an exception should be generated and bank account should get freezed.
I will solve the 1st one, 2nd case is your challenge.
#step-1: Create user-defined Exception class
class BalanceException(Exception):
pass#step-2:raise Exception for particular condition
balance = 1000
try:
amt = float(input("Enter the amount to withdraw:"))
#check remaining amount after transaction
temp = balance - amt
if temp < 100:
raise BalanceException("Insufficient balance")
except Exception as obj:
print(obj)In above snippet, we raised a custom exception if balance goes below 100$.
We want to do transaction if no exception has occurred. We can write else block.
else:
balance = balance - amtWeather exception occurs or not, we want to print remaining balance. We can use finally block for that.
finally:
print("Remaining balance is:",balance)
Now, add another Exception for second case and update code given.
Challenge
MediumYou have to add code for 2nd case.
Try it yourself
balance = 10000 #Imagine it is fetched from database.
class BalanceException(Exception):
pass
def transaction():
global balance
try:
amt = float(input())
#check remaining amount after transaction
temp = balance - amt
if temp < 100:
raise BalanceException("Insufficient balance")
except Exception as obj:
print(obj)
else:
balance = balance - amt
finally:
print("Remaining balance is:",balance)All lessons in Exception Handling in Python
4Customization/best practices
Customize Tracebacks3User-defined Exceptions
Types of ExceptionsRaising an ExceptionUser Defined ExceptionException Handling Exercise- 1Exception Handling Example-2Exception Handling Example-3