Help me understand basic error checking

Trying to do some basic error checking. Only started with Python a few days ago. I’m confused why the following code does not work. No matter whether I start the program with 3 or 4 arguments, I always get the error message, and I don’t understand why that happens. Similar code has worked for me before in other programs. Please enlighten me what is happening here.

–code starts–

some basic error checking

no_third_file = False
try:
outputfile = sys.argv[1]
inputfile1 = sys.argv[2]
inputfile2 = sys.argv[3]
inputfile3 = sys.argv[4]
except:
outputfile = sys.argv[1]
inputfile1 = sys.argv[2]
inputfile2 = sys.argv[3]
no_third_file = True
finally:
print(‘Not enough command line arguments found. Usage:’)
print(sys.argv[0], ‘outputfile inputfile1 inputfile2 inputfile3’)
print(‘Total output size is expected to be about two thirds of total input size’)
print(‘If only two input files are available, the third can be omitted’)
print(‘In that case, xor will be used to reconstruct the third file’)
quit()

Please enclose your code in triple backticks to preserve formatting:

```
YOUR CODE HERE
```

The finally clause of a try, except, finally statement always runs, regardless of what happened in the try and except clauses. Since you put your error message in the finally clause, it will always be printed.

Oftentimes, you only need the try and except clauses, while the finally clause can (should) be omitted. It is commonly used to clean up resources that may not be properly released otherwise.

In your case, I would say that a try, except statement in unsuitable for the problem you are trying to solve. You have three cases:

  1. Three command line arguments
  2. Four command line arguments
  3. Any other number of command line arguments

Distinguishing between these cases with a try, except statement cannot be done in a clean way, since the error case for case 2 and 3 is the same (IndexError). You would have to nest another try, except statement within the first except to catch the second error, which is not very nice. Furthermore, you won’t catch the error case where too many command line arguments were passed (if that should be considered as an error).

Instead, just use an if statement:

outputfile = sys.argv[1]
inputfile1 = sys.argv[2]
inputfile2 = sys.argv[3]
if len(sys.argv) == 4:
    has_third_file = False
elif len(sys.argv) == 5
    inputfile3 = sys.argv[4]
    has_third_file = True
else:
    raise ValueError("Too many arguments")

Also, avoid naming booleans as negatives. no_third_file=False is a double negative which is harder to parse for someone reading the code than has_third_file=True.

On a related note, never do this:

try:
    ...
except:
    ...

Always specify what exception you want to catch:

try:
    ...
except IndexError:
    ...

A bare except catches anything and everything, and will hide bugs from you.