JoshJohnson
JoshJohnson

Reputation: 113

How to properly handle multiple Runtime errors?

Program description:

Program accepts a file name and a segment, consisting of two numbers (each divided by one space). Then it outputs all lines from existing file where their indicies lie within the given segment.

My solution:

import sys
try:
    par = input("Input (<file> <low border of the segment> <high border of the segment>): ").split(' ')
    print(17 * '-')
    f = par[0]
    f_lines = [line.strip("\n") for line in f if line != "\n"]
    length = len(f_lines)
    if (par == ''):
        raise RuntimeError('Error: undefined')
    if (par[2] == None) or (par[2] == ''):
        raise RuntimeError('Error: segment is limited')
    if ((par[1] and par[2]) == None) or ((par[1] and par[2]) == ''):
        raise RuntimeError('Error: segment undefined')
    if (int(par[2]) >= length):
        raise RuntimeError('Error: segment can not be greater than length the amount of lines')
    if (par[1] == ''):
        a = 0
    if (par[2] == ''):
        b = 0
    segment = [int(par[1]), (int(par[2]) + 1)]
    with open(par[0]) as f:
        data = f.read().splitlines()
        for k in range(segment[0], segment[1]):
            print(data[k])
except (FileNotFoundError, IOError, NameError):
    print('[!] Error: your input is incorrect. The file may be missing or something else. \n[?] For further information see full error logs: \n',sys.exc_info())
except RuntimeError as e:
    print(e)

Problem:

When I try running my program in different ways to test each of my Runtime errors I always get this message:

Traceback (most recent call last):
  File "C:\Users\1\Desktop\IT\pycharm\sem_2.py", line 10, in <module>
    if (par[2] == None) or (par[2] == ''):
IndexError: list index out of range

I cannot wrap my head around how can I properly handle multiple Runtime errors so they would display as a text message. I haven't found any solution to my question anywhere online, so I'm trying to ask here.

I will appreciate any help, thanks in advance.

Upvotes: 0

Views: 189

Answers (1)

Czaporka
Czaporka

Reputation: 2407

Your code would catch FileNotFoundError, IOError, NameError and RuntimeError but what is actually thrown is IndexError and that is not handled.

You may want to add IndexError it to the first except block:

except (FileNotFoundError, IOError, NameError, IndexError):
    print('[!] Error: input incorrect!')   # ^^^^^^^^^^^^

or perhaps add another except block if you want a custom message for IndexError:

except (FileNotFoundError, IOError, NameError):
    print('[!] Error: input incorrect!')
except IndexError:
    print('[!] Error: IndexError just happened!')

By the way, the following will always be False because the code in parentheses will resolve to a bool first, which can either be True or False and these are obviously never equal to '' or None:

((par[1] and par[2]) == None) or ((par[1] and par[2]) == '')

You may way want to rewrite it to:

(par[1] is None and par[2] is None) or (par[1] == '' and par[2] == '')

Upvotes: 2

Related Questions