Example code - Exceptions

From 22101
Revision as of 16:54, 1 March 2024 by WikiSysop (talk | contribs) (Created page with "== Determining input type == How to determine the input with try/expect. This is not really how it is done in practice, but it is still good to understand the ideas, because sooner or later you run into a situation where parts of this is useful. <pre> inputstring = input("Enter something and I will guess what it is: ") try: # This assignment will succeed mytype = 'string' # This may fail, in such case our exception handler is called result = float(inputst...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Determining input type

How to determine the input with try/expect. This is not really how it is done in practice, but it is still good to understand the ideas, because sooner or later you run into a situation where parts of this is useful.

inputstring = input("Enter something and I will guess what it is: ")
try:
    # This assignment will succeed
    mytype = 'string'
    # This may fail, in such case our exception handler is called
    result = float(inputstring)
    mytype = 'floating point'
    # This may fail, in such case our exception handler is called
    result = int(inputstring)
    mytype = 'integer'
# The exception handler, do nothing
except ValueError:
    pass
# because we have already found the correct type, so print it
print("It is a", mytype)

Show first 10 lines in a file

Using exceptions to catch errors in the file name. This is very useful when you run the program from the command line. When using Jupyter Notebook, this is unfortunately not so practical as it kills the python kernel.

import sys
filename = input("Enter a filename: ")
try:
    # Will fail if there is no readable file by that name
    infile = open(filename, 'r')
except IOError as err:
    print("Can not open", filename, "Reason:", str(err))
    sys.exit(1)
count = 0
line = infile.readline()
while line != "" and count < 10:
    print(line, end='')
    count += 1
    line = infile.readline()
print("This is the first", count, "lines of", filename)