What Can Go Wrong Open a File for Writing

27 May 2013 | One-minute read


During a code review, I requested an intern to add a try-except block for some file handling code. (The language happen to be Python, but that isn’t really the point.) He had written

in_file = None
out_file = None
try:
    in_file = open(in_file_path, 'r')
except IOError:
    print 'Cannot open input file ', in_file_path
    return -1
out_file = open(out_file_name, 'w')

There was a try-except for the input file, but not for the output file. He asked me “What could go wrong, so why add the try-except”? Actually, quite a few things could go wrong.

A lot of things can go wrong when trying to open a file, and depending on your error handling strategy, you need to be prepared to catch those exceptions.