Python Exception Handling Part 2
except with multiple Exceptions
except statement can catch multiple Exceptions as shown in the program below.
x = int(input())
y = int(input())
name = input()
scores = [40,71,102,34]
batsmanruns = {"Dhoni":350, "Kohli":410, "Smith":212}
try:
scores[x] += 10
batsmanscore = batsmanruns[name]
assert (y > 9), "Very Small Number"
except (IndexError, AssertionError):
print ("First except")
except KeyError:
print ("Second except")
else:
print ("All Fine")
- If the input values are 0 100 John, the output is "Second Except" as KeyError is raised for John
- If the input values are 1 40 Dhoni, the output is "All Fine" as there is no Exception raised. - If the input values are 2 5 Kohli, the output is "First Except" as AssertionError is raised as the condition 5 > 9 is False.
- If the input values are 9 100 Smith, the output is "First Except" as IndexError is raised for 9
the below program prints "Success" only when the input value for index is 4 or 5. Else it must print "Failure".
x = 3
index = int(input())
pricelist = [100,200,300,400,500,600]
try:
assert (index > x), "Invalid"
pricelist[index] += 10
except (IndexError, AssertionError):
print ("Failure")
else:
print ("Success")
try with finally
finally statement is used to execute a code irrespective of whether an Exception occurs or not.
The below program will print "The End" irrespective of the input value.
index = int(input())
pricelist = [100,200,300,400,500,600]
try:
pricelist[index] += 10
except IndexError:
print ("Invalid Index")
else:
print ("Success")
finally:
print ("The End")
- If the input value is 2, the output is
Success
The End
- If the input value is 12, the output is
Invalid Index
The End
Another program:
key = input()
countrycapital = {"India":"Delhi", "Srilanka":"Colombo", "China":"Beijing", "Cuba":"Havana", "Germany":"Berlin"}
try:
capital = countrycapital[key]
except KeyError:
print ("Key Not Present")
else:
print (capital)
finally:
print("Done")
Input:
Germany
Output:
Berlin
Done
Raising Exception - raise statement
We can raise an Exception using raise statement.
The syntax for the raise statement is
raise Exception [Arguments]
The below program raises an Exception with the message "The shirt size is not present" when the size is greater than 50 or less than 16.
shirtsize = int(input())
try:
if(shirtsize > 50 or shirtsize < 16):
raise Exception("The shirt size is not present")
print ("Size is Available")
except Exception as e:
print (str(e))
- If the input is 34, the program prints "Size is Available"
- If the input is 11, the program prints "The shirt size is not present"
- If the input is 54, the program prints "The shirt size is not present"
the program raises an Exception with the input value message, if the input value price is more than 1000. Else (if the input price is less than 1000) print "Add To Cart"
price = int(input())
message = input()
try:
if(price > 1000):
raise Exception(message)
print("Add To Cart")
except Exception as e:
print (str(e))
Custom (User Defined) Exceptions
User defined Exceptions can be created by extending in built Exceptions. To raise an Exception when ever the transaction amount is more than 50000 or less than 10, we create the following class TransactionAmountException as shown below.
class TransactionAmountException(Exception):
def __init__ (self,arg):
super().__init__(arg)
The calling code Hello.py is shown below.
from TransactionAmountException import TransactionAmountException
txnAmount = int(input())
try:
if(txnAmount > 50000 or txnAmount < 10):
raise TransactionAmountException("Invalid Transaction Amount")
print ("Valid Transaction Amount")
except TransactionAmountException as e:
print (e)
Comments
Post a Comment