Python Exception Handling Part 1

Python Exception Handling Part 1

Exceptions and Assertions 
Python provides Exceptions to handle any unexpected error. Assertions add debugging capabilities in the programs. 

Assertions can be used to check for valid input and also for valid output. 

Exception is the base class for all Exceptions. As an example, the KeyError raised when the specified key is not found in the dictionary is an example of Exception. 

To begin with let us know about Assertion. Below is the syntax for Assertion. 

assert Expression [, arguments] 

The below program checks (asserts) that the age of a person cannot be a negative value. The program execution will stop when -10 is passed as the value for age raising an AssertionError. 

def checkAgeAndPrint(age):
    assert (age >= 0), "Age Cannot Be Negative" 
     print (age)
    
checkAgeAndPrint(30) 
checkAgeAndPrint(-10) 
checkAgeAndPrint(20) 

The output of the program will be like 
30 
Traceback (most recent call last): 
 File "Hello.py", line 6, in <module>  
  checkAgeAndPrint(-10)  
File "Hello.py", line 2, in checkAgeAndPrint 
 assert (age >= 0), "Age Cannot Be Negative" 
AssertionError: Age Cannot Be Negative 

We can catch the AssertionError and print a relevant output message as in the program given below. 

def checkAgeAndPrint(age): 
    assert (age >= 0), "Age Cannot Be Negative" 
     print (age)
try: 
checkAgeAndPrint(30) 
        checkAgeAndPrint(-10) 
        checkAgeAndPrint(20) 
except AssertionError as ae: 
print(ae)

The output of the program given above is 
30 
Age Cannot Be Negative

try and except - IndexError 
IndexError is raised when an invalid index (out of bounds index) is used to retrieve the value as shown in the program below. 

numbers = [1,2,3,4,5] 

try: 
print (numbers[1]) 
print (numbers[9]) 

except IndexError as ie: 
print (ie) 

The output of the above program is 
list index out of range

the below program deals with the IndexError and prints the message "Invalid Index"

marks = [66,45,87]

try:
    print (marks[5])
except IndexError:
    print("Invalid Index")

try except else 
else block can be combined with try except. The code in the else block gets executed when there is NO exception raised within the try block. 

The program below prints the revised value if the index passed is from 0 to 4 (As there are 5 values in the list numbers). If any other value is passed it prints the output "Invalid Index". 

numbers = [66,45,87,56,90] 
index = int(input()) 

try: 
numbers[index] += 5 
except IndexError: 
print ("Invalid Index") 
else: 
print ("Revised Value = %d" %(numbers[index])) 

- If the input value is 1, the program prints "Revised Value = 50" 
- If the input value is 3, the program prints "Revised Value = 61" 
- If the input value is 9, the program prints "Invalid Index" 

Thus we see that the else block is executed only when there is no Exception raised in the try block.

the below program prints "Valid" when the input value for x is from 1 to 100 and prints "Invalid" for any other input value.

x = int(input())
try:
    assert(1 <= x and x <= 100)
except AssertionError:
    print ("Invalid")
else:
    print("Valid")

except without Exception(s) 

except statement can also be without any Exceptions. In such a scenario, the except block code is executed if any Exception is raised in the try block code. 
This can be used to catch all kinds of Exceptions without having to mention each of the Exceptions that can be possibly raised within the try block code. 

The drawback is because it catches all Exceptions, we cannot take corrective action specific to a particular Exception. Hence this is not considered as a good programming practice. 

Consider the program given below. (You can notice that the except catches all types of Exceptions raised) 

index = int(input()) 
values = [0,1,2,3] 
try: 
values[index] += 100 
except: 
print ("Exception Occurred") 
else: 
print ("No Exception") 

It prints "No Exception" when the input value is from 0 to 3. Else it prints "Exception Occurred".

Comments