Raise exception vs. return None in functions?

Viewed 53437

What's better practice in a user-defined function in Python: raise an exception or return None? For example, I have a function that finds the most recent file in a folder.

def latestpdf(folder):
    # list the files and sort them
    try:
        latest = files[-1]
    except IndexError:
        # Folder is empty.
        return None  # One possibility
        raise FileNotFoundError()  # Alternative
    else:
        return somefunc(latest)  # In my case, somefunc parses the filename

Another option is leave the exception and handle it in the caller code, but I figure it's more clear to deal with a FileNotFoundError than an IndexError. Or is it bad form to re-raise an exception with a different name?

5 Answers

with python 3.5's typing:

example function when returning None will be:

def latestpdf(folder: str) -> Union[str, None]

and when raising an exception will be:

def latestpdf(folder: str) -> str 

option 2 seem more readable and pythonic

(+option to add comment to exception as stated earlier.)

Related