Exceptions

Acknowledgement : the contents of this notebook are partially based on the book "Starting Out with Python (3rd Edition)".

An exception is an error that occurs while a program is running, causing the program to abruptly halt. You can use the try/except statement to gracefully handle exceptions.

In [7]:
# This program divides a number by another number

def main():
    # get two numbers
    num1 = int(input('Enter a number : '))
    num2 = int(input('Enter another number : '))
    
    # divide num1 by num2 and display the result
    result = num1 / num2
    print(num1,'divided by',num2,'is',result)
    
# call the main function
main()
Enter a number : 1
Enter another number : 0
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-7-b0223d636857> in <module>()
     11 
     12 # call the main function
---> 13 main()

<ipython-input-7-b0223d636857> in main()
      7 
      8     # divide num1 by num2 and display the result
----> 9     result = num1 / num2
     10     print(num1,'divided by',num2,'is',result)
     11 

ZeroDivisionError: division by zero
In [6]:
# preventing division by zero using an if statement

def main():
    # get two numbers
    num1 = int(input('Enter a number : '))
    num2 = int(input('Enter another number : '))
    
    # divide num1 by num2 and display the result
    if num2 != 0:
        result = num1 / num2
        print(num1,'divided by',num2,'is',result)
    else:
        print('Cannot divided by zero.')
        
# call the main function
main()
Enter a number : 1
Enter another number : 0
Cannot divided by zero.
In [8]:
# some exceptions cannot be avoided

def main():
    # get the numbers
    num1 = int(input('Enter an integer : '))
    
    # even or odd
    if num1 % 2 == 0:
        print(num1,'is an even number.')
    else:
        print(num1,'is an odd number.')

# call the main function
main()
Enter an integer : abc
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-8-e689d2df75f2> in <module>()
     12 
     13 # call the main function
---> 14 main()

<ipython-input-8-e689d2df75f2> in main()
      3 def main():
      4     # get the numbers
----> 5     num1 = int(input('Enter an integer : '))
      6 
      7     # even or odd

ValueError: invalid literal for int() with base 10: 'abc'

try/except statement

try:
     statement
     statement
     etc.
except ExceptionName:
     statement
     statement
     etc.

In [10]:
# handling exception
def main():
    
    try:
        # get the numbers
        num1 = int(input('Enter an integer : '))
    
        # even or odd
        if num1 % 2 == 0:
            print(num1,'is an even number.')
        else:
            print(num1,'is an odd number.')

    except ValueError:
        print('ERROR: the input must be an integer.')
        
# call the main function
main()
Enter an integer : abc
ERROR: the input must be an integer.
In [12]:
# this program displays the contents of a file
def main():
    # get the name of a file
    filename = input('Enter a filename : ')
    
    # open the file
    infile = open(filename,'r')
    
    # read the file's contents
    contents = infile.read()
    
    # display the file's contents
    print(contents)
    
    # close the file
    infile.close()
    
# call the main function
main()
Enter a filename : customer_record.txt
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-12-a61e998c4de3> in <module>()
     17 
     18 # call the main function
---> 19 main()

<ipython-input-12-a61e998c4de3> in main()
      5 
      6     # open the file
----> 7     infile = open(filename,'r')
      8 
      9     # read the file's contents

FileNotFoundError: [Errno 2] No such file or directory: 'customer_record.txt'
In [14]:
# this program displays the contents of a file (with try/except)
def main():
    # get the name of a file
    filename = input('Enter a filename : ')
    
    try:
    
        # open the file
        infile = open(filename,'r')
    
        # read the file's contents
        contents = infile.read()
    
        # display the file's contents
        print(contents)
    
        # close the file
        infile.close()
    
    except FileNotFoundError:
        print('The file',filename,'cannot be found.')
    
# call the main function
main()
Enter a filename : customer_record.txt
The file customer_record.txt cannot be found.

Handling Multiple Exceptions

In [16]:
# this program displays the total of the amounts in the file
def main():
    # initialize the accumulator
    total = 0.0
    
    try:
        # open the sales_data.txt file
        infile = open('sale_data.txt','r')
        
        # read the values from the file and accumulate them
        for line in infile:
            amount = float(line)
            total += amount
        
        # close the file
        infile.close()
        
        # print the total
        print(format(total,',.2f'))
        
    except FileNotFoundError:
        print('The file sales_data.txt cannot be found.')
        
    except ValueError:
        print('Non-numeric data found in the file.')
        
    except: # catch all other exceptions
        print('An error occured.')
        
# call the main function
main()
The file sales_data.txt cannot be found.

Display an Exception's Default Error Message

except ValueError as err:

In [18]:
# this program displays the total of the amounts in the file
def main():
    # initialize the accumulator
    total = 0.0
    
    try:
        # open the sales_data.txt file
        infile = open('sale_data.txt','r')
        
        # read the values from the file and accumulate them
        for line in infile:
            amount = float(line)
            total += amount
        
        # close the file
        infile.close()
        
        # print the total
        print(format(total,',.2f'))
        
    except FileNotFoundError as err:
        print(err)
        
    except ValueError as err:
        print(err)
        
    except: # catch all other exceptions
        print('An error occured.')
        
# call the main function
main()
[Errno 2] No such file or directory: 'sale_data.txt'
In [ ]:
# this program displays the total of the amounts in the file
def main():
    # initialize the accumulator
    total = 0.0
    
    try:
        # open the sales_data.txt file
        infile = open('sales_data.txt','r')
        
        # read the values from the file and accumulate them
        for line in infile:
            amount = float(line)
            total += amount
        
        # close the file
        infile.close()
        
        # print the total
        print(format(total,',.2f'))
        
    except Exception as err: # catch all exceptions
        print(err)
        
# call the main function
main()

The else clause

try:
     statement
     statement
     etc.
except ExceptionName:
     statement
     statement
     etc.
else:
     statement
     statement
     etc.

The statements in the else suite are executed after the statements in the try suite, only if no exceptions were raised. If an exception is raised, the else suite is skipped.

The finally clause

try:
     statement
     statement
     etc.
except ExceptionName:
     statement
     statement
     etc.
finally:
     statement
     statement
     etc.

The statements in the finally suite are always executed after the try suite has executed and after any exception handlers have executed. The statements in the finally suite execute whether an exception occurs or not.

In [ ]:
 
In [ ]:
 
In [ ]: