0

Does the code below provide correct exception handling. My goal is, to not attempt the file.write() unless the file was successfully opened and ensure the file is closed. I am not concerned with the exact errors of why the file did not open or why the file did not write.

Python version 3.6.9. OS Linux.

data = "Some data"
filename = "test.txt"

try:
    file = open(filename, 'w+')
except:
    print("Error opening file")
else:
    try:
        file.write(data)
    except:
        print("Error writing to file")
finally:
    file.close()
user264427
  • 5
  • 1
  • 4
  • Look at [What is a good way to handle exceptions when trying to read a file in python?](https://stackoverflow.com/questions/5627425/what-is-a-good-way-to-handle-exceptions-when-trying-to-read-a-file-in-python) – Nilesh Bhave Apr 12 '22 at 04:22
  • A context handler (`with open`) would simplify this. You should basically never use a blanket `except`; always spell out which exception(s) exactly you want to handle. – tripleee Apr 12 '22 at 04:50
  • I have updated my question to make the requirements of the code clearer. – user264427 Apr 12 '22 at 04:52
  • @tripleee I removed the code from the comments. Given the requirements of the code can you supply the correct code using with open ? – user264427 Apr 12 '22 at 05:50

1 Answers1

2

You should basically never use a blanket except; always spell out which exception(s) exactly you want to handle.

Here is a refactoring using a context handler, so you can avoid the explicit finally: close

data = "Some data"
filename = "test.txt"

try:
    with open(filename, 'w+') as file:
        try:
            file.write(data)
        except (IOError, OSError):
            print("Error writing to file")
except (FileNotFoundError, PermissionError, OSError):
    print("Error opening file")

There may be more exceptions you should enumerate; I rattled these off off the top of my head.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Other than by replicating all the possible ways an error could occur, what's the best way of working out what all the possible exceptions are that need to be handled? You invariably may not think of all possible errors that could occur, and without having a suitable list how would you know what exceptions to check for? I got to this question for example by searching for all possible "write to file" exceptions. – Maikol Aug 25 '23 at 07:59
  • https://stackoverflow.com/a/10594142/874188 explains why a blanket `except:` is problematic. If the code in the `try:` is absolutely trivial, you can probably get away with it, but then of course, you will then risk making the code in that block more complex later on, and then bump into unpleasant situations because of the bare `except` after all. For common errors, you can probably enumerate the likely exceptions without a lot of work, but in the general case, you'd basically have to study Python's exception hierarchy and figure out which ones could be caused by your code. – tripleee Aug 25 '23 at 16:36