Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python try:except:finally

# Open new file to write
file = None
try:
    file = open(filePath, 'w')
except IOError:
    msg = ("Unable to create file on disk.")
    file.close()
    return
finally:
    file.write("Hello World!")
    file.close()

The above code is ripped from a function. One of the user's system is reporting an error in line:

file.write("Hello World!")

error:

AttributeError: 'NoneType' object has no attribute 'write'

Question is, If python is failed to open given file, 'except' block executes and it has to return, but control is getting transferred to the line that is throwing given error. The value of 'file' variable is 'None'.

Any pointers?

like image 417
user354051 Avatar asked Oct 15 '11 11:10

user354051


People also ask

Can we use try Except And finally in Python?

The try block lets you test a block of code for errors. The except block lets you handle the error. The else block lets you execute code when there is no error. The finally block lets you execute code, regardless of the result of the try- and except blocks.

When to use try except finally?

The try... except statement allows you to catch one or more exceptions in the try clause and handle each of them in the except clauses. The finally clause always executes whether an exception occurs or not. And it executes after the try clause and any except clause.

How do you handle exception with try finally in Python?

When an exception is thrown in the try block, the execution immediately passes to the finally block. After all the statements in the finally block are executed, the exception is raised again and is handled in the except statements if present in the next higher layer of the try-except statement.

How do you end a Python try?

finally ..." in Python. In Python, try and except are used to handle exceptions (= errors detected during execution). With try and except , even if an exception occurs, the process continues without terminating. You can use else and finally to set the ending process.


Video Answer


3 Answers

You shouldn't be writing to the file in the finally block as any exceptions raised there will not be caught by the except block.

The except block executes if there is an exception raised by the try block. The finally block always executes whatever happens.

Also, there shouldn't be any need for initializing the file variable to none.

The use of return in the except block will not skip the finally block. By its very nature it cannot be skipped, that's why you want to put your "clean-up" code in there (i.e. closing files).

So, if you want to use try:except:finally, you should be doing something like this:

try:
    f = open("file", "w")
    try:
        f.write('Hello World!')
    finally:
        f.close()
except IOError:
    print 'oops!'

A much cleaner way of doing this is using the with statement:

try:
    with open("output", "w") as outfile:
        outfile.write('Hello World')
except IOError:
    print 'oops!'
like image 169
Acorn Avatar answered Sep 23 '22 01:09

Acorn


If the file is not opened, the line file = open(filePath, 'w') fails, so nothing gets assigned to file.

Then, the except clause runs, but nothing is in file, so file.close() fails.

The finally clause always runs, even if there was an exception. And since file is still None you get another exception.

You want an else clause instead of finally for things that only happen if there was no exception.

    try:
        file = open(filePath, 'w')
    except IOError:
        msg = "Unable to create file on disk."
        return
    else:
        file.write("Hello World!")
        file.close()

Why the else? The Python docs say:

The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try ... except statement.

In other words, this won't catch an IOError from the write or close calls. Which is good, because then reason woudn't have been “Unable to create file on disk.” – it would have been a different error, one that your code wasn't prepared for. It's a good idea not to try to handle such errors.

like image 39
Petr Viktorin Avatar answered Sep 21 '22 01:09

Petr Viktorin


what is the logic in including the

file.write("Hello World!")

inside the finally clause?? i think it must be put in try clause itself.

try:
        file = open(filePath, 'w')
        file.write("Hello World!")
except IOError:
        print("Unable to create file on disk.")
finally:
        file.close()
like image 39
Sreenath Nannat Avatar answered Sep 21 '22 01:09

Sreenath Nannat