What is the best practice?

In python code, error conditions are usually indicated with exceptions. You could use raise ValueError("Arrays must have the same size").

Using exception rather than return values to indicate errors has the added advantage that the exception would bubble up until it reaches a except statement. So you can defer the error handling up to a place where it makes sense. Also exceptions have an associated descriptive message instead of a magic number.

The break statement, as in many other languages, is used to interrupt the flow in loops, like ones created with while or for.

Answer from memoselyk on Stack Overflow
🌐
Finxter
blog.finxter.com › home › learn python blog › python return error from function
Python Return Error From Function - Be on the Right Side of Change
October 26, 2022 - The best practice solution to indicate that there was an error in a Python function is not to return a dummy value but to raise an error using syntax such as raise ValueError("...
Discussions

What does "script xyz.py returned exit code 0" mean in Python? - Stack Overflow
I got a message saying script xyz.py returned exit code 0. What does this mean? What do the exit codes in Python mean? How many are there? Which ones are important? More on stackoverflow.com
🌐 stackoverflow.com
Error return function
Lambda may accept multiple arguments and may return only one expression. Here, it appears as if you are attempting to do it backwards. You are giving it one argument ( a list counts as one argument here), and attempting to return multiple expressions, as noted by the commas · I don’t believe ... More on discuss.python.org
🌐 discuss.python.org
0
0
February 17, 2024
Error handling in functions that returns a value
This: Raise the error or another error and make a second try block at the function call? Btw you also might want to consider using existing implementations, eg pathlib.Path.read_text or read_bytes instead of implementing your own 'get file content' function. More on reddit.com
🌐 r/learnpython
4
1
January 24, 2022
Best practice in python for return value on error vs. success - Stack Overflow
Both the programmer and the user of the functions know what to expect. ... +1: I was about to answer the same :-D Exceptions are, as their name indicates, for exceptional situations, for validating inputs that you except to be faulty on a normal basis (e.g. input from keyboard), it's usually better to return an error code... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.3 documentation
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. Exception handlers do not handle only exceptions that occur immediately in the try clause, but also those that occur inside functions that are called (even indirectly) in the try clause. For example: >>> def this_fails(): ... x = 1/0 ... >>> try: ... this_fails() ... except ZeroDivisionError as err: ... print('Handling run-time error:', err) ...
🌐
Python.org
discuss.python.org › python help
Error return function - Python Help - Discussions on Python.org
February 17, 2024 - Lambda may accept multiple arguments and may return only one expression. Here, it appears as if you are attempting to do it backwards. You are giving it one argument ( a list counts as one argument here), and attempting to return multiple expressions, as noted by the commas · I don’t believe ...
🌐
Reddit
reddit.com › r/learnpython › error handling in functions that returns a value
r/learnpython on Reddit: Error handling in functions that returns a value
January 24, 2022 -

Is there a best practise for error handling in functions that returns a value?

Example

There is a function get_file_content() for opening a text document that should return the content of the file as a string.

def get_file_content(path):
    return file.open(path) 

Now I could expand the function with a try block.

def get_file_content(path):
    try:         
        return file.open(path)
    except SomeError:
        //Logging some error 

But what to use as a return value?

  • None? An empty string?

  • Raise the error or another error and make a second try block at the function call?

  • Or return some integer which is checked at the function call?

  • Or return a tuple with the string from the text file or an empty string and a boolean if the function have been successful?

I know that it could not be answered generally but maybe there are some best practice or real life examples.

Find elsewhere
Top answer
1 of 7
77

First, whatever you do don't return a result and an error message. That's a really bad way to handle errors and will cause you endless headaches. If you need to indicate an error always raise an exception.

I usually tend to avoid raising errors unless it is necessary. In your example throwing an error is not really needed. Intersecting an empty list with a non empty one is not an error. The result is just empty list and that is correct. But let's say you want to handle other cases. For example if the method got a non-list type. In this case it is better to raise an exception. Exception are nothing to be afraid of.

My advice for you is to look at the Python library for similar functions and see how Python handles those special cases. For example have a look at the intersection method in set, it tends to be forgiving. Here I'm trying to intersect an empty set with an empty list:

>>> b = []
>>> a = set()
>>> a.intersection(b)
set([])

>>> b = [1, 2]
>>> a = set([1, 3])
>>> a.intersection(b)
set([1])

Errors are only thrown when needed:

>>> b = 1
>>> a.intersection(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

Sure, there are cases where returning True or False on success or failure can be good. But it is very important to be consistent. The function should always return the same type or structure. It is very confusing to have a function that could return a list or a boolean. Or return the same type but the meaning of this value can be different in case of an error.

EDIT:

The OP says:

I want to return something to indicate the parameters were incorrect.

Nothing says there is an error better than an exception. If you want to indicate the parameters are incorrect then use exceptions and put a helpful error message. Returning a result in this case is just confusing. There might other cases where you want to indicate that nothing has happened but it is not an error. For example if you have a method that deletes entries from a table and the entry requested for deletion does not exist. In this case it might be fine to just return True or False on success or failure. It depends on the application and the intended behaviour

2 of 7
26

It'd be better to raise an exception than return a special value. This is exactly what exceptions were designed for, to replace error codes with a more robust and structured error-handling mechanism.

class IntersectException(Exception):
    def __init__(self, msg):
        self.msg = msg
    def __str__(self):
        return self.msg

def intersect_two_lists(self, list1, list2):
    if not list1:
        raise IntersectException("list1 must not be empty.")
    if not list2:
        raise IntersectException("list2 must not be empty.")

    #http://bytes.com/topic/python/answers/19083-standard
    return filter(lambda x:x in list1,list2)

In this specific case though I'd probably just drop the tests. There's nothing wrong with intersecting empty lists, really. Also lambda is sort of discouraged these days in preference to list comprehensions. See Find intersection of two nested lists? for a couple of ways to write this without using lambda.

🌐
Luke Plant
lukeplant.me.uk › blog › posts › raising-exceptions-or-returning-error-objects-in-python
Raising exceptions or returning error objects in Python - lukeplant.me.uk
June 6, 2022 - In particular, if you want to hand ... other function or code for handling, you can’t do it easily. For example, code like this would be fine with the “return error object” method, but significantly complicated by the “raise exception” method: verify_result = verifier.email_from_token(token) ...
🌐
CodeRivers
coderivers.org › blog › python-return-error
Understanding and Handling Python Return Errors - CodeRivers
April 6, 2025 - Some Python linters may flag this as an error. Functions often expect a specific data type to be returned. If the wrong data type is returned, it can lead to errors. For example: def get_sum(a, b): return a + b result = get_sum(2, 3) # This works fine as the function returns an integer def ...
🌐
Victoria
victoria.dev › posts › do-i-raise-or-return-errors-in-python
Do I Raise or Return Errors in Python? | victoria.dev
February 9, 2021 - Here’s something I’ve started caring about more as codebases grow: how well does your choice play with static type checking? Modern Python with type hints changes the game significantly. With exceptions, your function signature stays clean: def parse_user_id(user_input: str) -> int: try: return int(user_input) except ValueError: raise InvalidUserIdError("User ID must be a number")
🌐
Medium
medium.com › @luzhenna › python-error-handling-return-instead-of-raise-2395da8754e7
Deferred Error Handling in Python: Return instead of Raise | by Lu Zhenna | Medium
August 20, 2024 - Deferred Error Handling in Python: Return instead of Raise Summary This article shows a different way of handling errors in Python — deferred error handling. If exceptions or errors were returned …
🌐
Initial Commit
initialcommit.com › blog › return-outside-function
Return Outside Function error in Python
March 18, 2021 - However, all return statements must be part of a function block - and since this one doesn’t match the indentation level of the function scope, Python raises the error. This problem has a simple solution, and that's to indent the return statement the appropriate number of spaces: Now, the return statement doesn't break the red line. It's been moved over four spaces to be included inside the function block. When you run this code from a file or in the interpreter, you get the correct result:
Top answer
1 of 3
1

If you do want to raise an exception instead of returning -1 when the file doesn't exist, you could skip the check() and go directly to open() or whatever you actually want to do with the file.

The correct way to actually raise the exception is to let it get raised. So do:

def check_and_open(file):
    # raises FileNotFoundError automatically
    with open('xyz', 'r') as fp:
        fp.readlnes()  # or whatever

And if you do want to explicitly check before you open, this will raise the actual error object:

def check(file):
    try:
        with open(file, 'r') as fp:
            # continue doing something with `fp` here or 
            # return `fp` to the function which wants to open file
            pass
    except FileNotFoundError as e:
        # log error, print error, or.. etc.
        raise e  # and then re-raise it

Result of this version is:

>>> check('xyz')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 9, in check
  File "<stdin>", line 3, in check
FileNotFoundError: [Errno 2] No such file or directory: 'xyz'
>>>

Also, note that just doing raise FileNotFoundError(file), like in another answer provided, breaks how FileNotFoundError actually raises:

Raising explicitly (the filename gets considered as the err message):

>>> raise FileNotFoundError('xyz')
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
FileNotFoundError: xyz
>>>

How it's actually raised by Python:

>>> fp = open('xyz', 'r')
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'xyz'
>>>
>>> # or with `with`:
... with open('xyz', 'r') as fp:
...     fp.readlnes()
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'xyz'
>>>
2 of 3
0

You could raise an exception (FileNotFoundError is used in built-in libraries), although if you'll try to use non-existent file you'll get FileNotFoundError exception raised by default.

Then, when using this function, handle your exception:

import os

def check(file):
    if not os.path.exists(file):
        raise FileNotFoundError(file)

if __name__ == '__main__':
    try:
        check(os.path.join('foo', 'bar'))
    except FileNotFoundError:
        print('File was not found')
🌐
Python
docs.python.org › 3 › c-api › exceptions.html
Exception Handling — Python 3.14.3 documentation
It calls the Win32 function FormatMessage() to retrieve the Windows description of error code given by ierr or GetLastError(), then it constructs a OSError object with the winerror attribute set to the error code, the strerror attribute set to the corresponding error message (gotten from FormatMessage()), and then calls PyErr_SetObject(PyExc_OSError, object). This function always returns NULL.
🌐
Quora
quora.com › What-is-the-exit-status-code-of-a-Python-script
What is the exit status code of a Python script? - Quora
... Software Developer at Goethe ... in python 3, ends the running python process. The function takes an integer argument that returns the exit code from the Python process....
🌐
Notes
henryleach.com › 2025 › 02 › controlling-python-exit-codes-and-shell-scripts
Controlling Python Exit Codes and Shell Scripts - Henry Leach
February 9, 2025 - #!/bin/sh eval python exit-examples.py return_code=$? if [ $return_code = 0 ]; then echo "Success!" elif [ $return_code = 1 ]; then echo "Mild panic!" elif [ $return_code = 42 ]; then echo "Other fallback" else echo "Real Failure" exit $return_code fi · Which might be useful for kicking off other processes, or not, that it's not possible to manage from Python, and would be less error prone than trying to grep messages from stdout in your shell script.
Top answer
1 of 2
5

There is no such function. You couldn't build a function that does what you ask for, because by the time Python calls iserror(), the float('123') or float('as1f') expression has already been executed; if an exception is raised there, iserror() is never executed.

You'd have to delegate calling to the function:

def iserror(func, *args, **kw):
    try:
        func(*args, **kw)
        return False
    except Exception:
        return True

then use it like this:

iserror(float, '123')   # False
iserror(float, 'as1f')  # True

Catching all errors is not that great an idea however. Although the above function tries to do the right thing by catching Exception (and thus avoids catching SystemExit or KeyboardInterrupt), it will catch MemoryError, which indicates you ran out of memory, not that the arguments to the function you tested were wrong!

Always try to catch specific exceptions; you could extend iserror() to take a specific exception:

def iserror(func, *args, **kw):
    exception = kw.pop('exception', Exception)
    try:
        func(*args, **kw)
        return False
    except exception:
        return True

then only catch ValueError to test your float() calls:

iserror(float, '123', exception=ValueError)   # False
iserror(float, 'as1f', exception=ValueError)  # True

This is no longer all that readable. I'd just stick with a simple inline try..except wherever you want to use a function call that could raise an exception, because then you can tailor your response to the specific exception without having to repeat yourself to handle the result after you determined there won't be an error:

while True:
    value = raw_input('Please give a number: ')
    try:
         value = int(value)
         break
    except ValueError:
         print "Sorry, {} is not a valid number, try again".format(value)
2 of 2
0

While there is no such function for the general case, there is one that solves your particular problem:

x = '123'
x.isnumeric()

returns True

while

x = 'as1f'
x.isnumeric()

returns False