Chengming Gu
Chengming Gu

Reputation: 67

Print statement is not working in try catch else finally block

I use Try Catch Else Finally block to create this function.

Here is my code:

def read_a_file():
    """
    >>> out = read_a_file() #while the file is not there
    The file is not there.
    We did something.
    >>> print(out)
    None
    >>> Path('myfile.txt').touch()
    >>> out = read_a_file() #while the file is there
    The file is there!
    We did something.
    >>> type(out)
    <class '_io.TextIOWrapper'>
    >>> out.close()
    >>> os.remove("myfile.txt")
    """
    try:
        file_handle = open('myfile.txt', 'r')
        return file_handle
    except FileNotFoundError:
        print('The file is not there.')
        return None
    else:
        print('The file is there!')
    finally:
        print('We did something.')

However, when I run the doctest, the print statement never work in except and else block. Only the print statement in finally block is working.

I got this as result, which is not what I wanted.

>>> out = read_a_file() #while the file is not there
We did something.

Help!!! How to solve this issue?

You have to import these packages

import pandas as pd
from functools import reduce
from pathlib import Path
import os

Upvotes: 0

Views: 1603

Answers (1)

Tim Peters
Tim Peters

Reputation: 70602

This has nothing to do with doctest. The behavior is expected because, when you return, the else: clause is not executed. From the docs:

The optional else clause is executed if and when control flows off the end of the try clause. [2]

...

[2] Currently, control “flows off the end” except in the case of an exception or the execution of a return, continue, or break statement.

So if you want The file is there!to appear if and only if no exception is raised, lose the else: clause and move

print('The file is there!')

above

return file_handle

Upvotes: 4

Related Questions