This means the exception has no message attached. Print the exception type:

print repr(e)

You may also want to print the traceback:

import traceback

# ...
except BaseException as e:
    traceback.print_exc()

You want to avoid catching BaseException however, this is no better than a blanket except: statement. Catch more specific exceptions instead.

Answer from Martijn Pieters on Stack Overflow
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ exceptions.html
Built-in Exceptions โ€” Python 3.14.4 documentation
The base class for all built-in exceptions. It is not meant to be directly inherited by user-defined classes (for that, use Exception). If str() is called on an instance of this class, the representation of the argument(s) to the instance are returned, or the empty string when there were no ...
Discussions

Should you return an empty list on error or nothing?
Depends on how it is being used. also pay attention to naming. The current name I weould probably expect it to give me an empty list. But something like entities_exist I would expect none or false More on reddit.com
๐ŸŒ r/learnpython
7
2
October 19, 2020
How to catch empty user input using a try and except in python? - Stack Overflow
Thanks for posting your code, but ... what is the result you expect, and what have you tried so far? Going through the question checklist will help us better answer your question. Thanks! ... If you literally want to raise an exception only on the empty string, you'll need to do that manually: try: user_input = input() # raw_input in Python 2.x if not ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Python: Queue.Empty Exception Handling - Stack Overflow
The other argument is that either way is acceptable in Python and that handling the task outside of the try/except could aid debugging if task handling is large, although agreed that this might look uglier than using Method 2. ... UPDATE: A little more info after answer 1 came through.... The debate was started after method 1 was using in some multithreaded code. In which case, the code will acquire the lock (from a threading.Lock object) and release it either once the task it returned or Queue.Empty ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Try-except clause with an empty except code - Stack Overflow
Generally to the empty catch block: ... to love empty catch blocks. I don't know why you would do this but finding an error in such an application is horrible. You see from the results that something went wrong but to tackle it you have to work a lot with MsgBox and stuff. Martin K. โ€“ Martin K. 2014-06-16 17:48:06 +00:00 Commented Jun 16, 2014 at 17:48 ... Ignoring a specific exception by using pass in the except block is totally fine in Python... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
CodeQL
codeql.github.com โ€บ codeql-query-help โ€บ python โ€บ py-empty-except
Empty except โ€” CodeQL query help documentation
The loss of information can lead to hard to debug errors and incomplete log files. It is even possible that ignoring an exception can cause a security vulnerability. An empty except block may be an indication that the programmer intended to handle the exception, but never wrote the code to do so.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ should you return an empty list on error or nothing?
r/learnpython on Reddit: Should you return an empty list on error or nothing?
October 19, 2020 -

I have the below code:

def get_entities(self, table_name: str) -> list:
    """
    Returns a list of entities from a specified table
    :param table_name: table name
    :return: list of entities from a table
    """
    try:
        return list(self.service.query_entities(table_name))
    except Exception as e:
        logger.warning(e)

If the request fails it won't return anything. Code further on will try to iterate the returned list, but if no list is returned it errors at that point.

Is it better to return an empty list:

def get_entities(self, table_name: str) -> list:
    try:
        return list(self.service.query_entities(table_name))
    except Exception as e:
        logger.warning(e)
    return [] # fallback

Or to check the return value before iterating the expected list?

entities = get_entities(table_name="test123")
if entities is not None:
    for entity in entities:
        print(entity)

I feel like returning an empty list would just be masking the issue?

๐ŸŒ
Firas
firas.io โ€บ posts โ€บ python exception handling
Python Exception Handling | Firas Sadiyah
February 25, 2024 - First, we can check if the DataFrame is non-empty before applying any logic in each mini-function. Second, we can make the pipeline function fail graciously if it receives an empty DataFrame from any of the mini-functions by using a custom exception and a try-except block. Letโ€™s take a look. At times, Python code encounters errors that halt program execution.
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ c-api โ€บ exceptions.html
Exception Handling โ€” Python 3.14.4 documentation
Get the end attribute of the given exception object and place it into *end. end must not be NULL. Return 0 on success, -1 on failure. If the UnicodeError.object is an empty sequence, the resulting end is 0.
Find elsewhere
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ What-is-the-best-way-to-handle-list-empty-exception-in-Python
What is the best way to handle list empty exception in Python?
December 19, 2019 - List is an ordered sequence of elements. Individual element in list is accessed using index starting with 0 and goes up to length-1. If index goes beyond this range, IndexError exception is encountered. In following example, an infinite loop
Top answer
1 of 3
4

The thing that I think you're missing here is that the StopIteration is what actually makes the for loop stop. This is why you can write custom iterators that work with Python's for loop transparently. It doesn't do any checking to see if the iterator is empty, and the for loop does not keep track of of the iterator's state. This is an effect of the iterator protocol, and was an intentional choice in the language design. You can read more about the iterator protocol on Python's docs site if you want to.

It also makes more sense if you think about the number of items in e.g. your list corresponding directly to the number of times your loop is executed.

-----------------------------------|
| No. of items | No. times executed|
------------------------------------
|      5       |         5         |
|      4       |         4         |
|      3       |         3         |
|      2       |         2         |
|      1       |         1         |
|      0       |         0         |
------------------------------------

If the for loop special-cased an empty iterable, this invariant would be lost.

It would also complicate the protocol on writing custom iterators, because you would have to have an extra method to signal to the for loop that your iterable is empty before the iteration began.

Here's a (stupid) example of a custom iterator that always acts like it's empty:

class EmptyIterator():
    def __iter__(self): return self
    def __next__(self): raise StopIteration

for blah in EmptyIterator():
    print('this is never reached')
try:
    next(EmptyIterator())
except StopIteration:
    print('Oh hi, I was empty so I raised this Exception for you.')
2 of 3
10

This is odd to me. Why should an empty collection be treated any differently?

Forcing the programmer to check if the collection is empty before doing things to it would be a widespread, problematic sort of burden. Worse, an empty collection is in no way exceptional.

Personally, I would rather have the occasional bug where a no-op happened because I forgot to check for the rare case where I wanted different behavior on an empty collection rather than the occasional bug where an exception crashes my app because I forgot to say if empty, do nothing everywhere I wanted that common, expected behavior.

I mean, do you think printing empty strings should throw exceptions?

Top answer
1 of 4
19

The recommendation in Python is to use exceptions to indicate failure. This is true even if you expect failure on a regular basis.

Look at it from the perspective of the caller of your code:

my_status = get_abe_status(my_url)

What if we return None? If the caller doesn't specifically handle the case that get_abe_status failed, it will simply try to continue on with my_stats being None. That may produce a difficult to diagnose bug later on. Even if you do check for None, this code has no clue why get_abe_status() failed.

But what if we raise an exception? If the caller doesn't specifically handle the case, the exception will propagate upward eventually hitting the default exception handler. That may not be the what you want, but its better then introducing a subtle bug elsewhere in the program. Additionally, the exception gives information about what went wrong which is lost in the first version.

From the caller's perspective, its simply more convenient to get an exception than a return value. And that's the python style, to use exceptions to indicate failure conditions not return values.

Some will take a different perspective and argue that you should only use exceptions for cases you never really expect to happen. They argue that normally running running could should not raise any exceptions. One reason that is given for this is that exceptions are grossly inefficient, but that's not actually true for Python.

A couple of points on your code:

try:
    hits[0]
except IndexError:
    raise NotFoundError("No mentions found.")

That's a really confusing way to check for an empty list. Don't induce an exception just to check something. Use an if.

# say we expect four hits...
if len(hits) != 4:
    raise Warning("An unexpected number of hits.")
    logger.warning("An unexpected number of hits.")

You do realize that the logger.warning line will never run right?

2 of 4
4

The accepted answer deserves to be accepted and answers the question, I write this only to provide a bit of extra background.

One of Python's credos is: it's easier to ask forgiveness than permission. This means that typically you just do things, and if you expect exceptions, you handle them. As opposed to doing if checks before hand to make sure you won't get an exception.

I want to provide an example to show you how dramatic the difference is in mentality from C++/Java. A for loop in C++ typically looks something like:

for(int i = 0; i != myvector.size(); ++i) ...

A way to think about this: accessing myvector[k] where k >= myvector.size() will cause an exception. So you could in principle write this (very awkwardly) as a try-catch.

    for(int i = 0; ; ++i)  {
        try {
           ...
        } catch (& std::out_of_range)
             break

Or something similar. Now, consider what's happening in a python for loop:

for i in range(1):
    ...

How is this working? The for loop takes the result of range(1) and calls iter() on it, grabbing an iterator to it.

b = range(1).__iter__()

Then it calls next on it at each loop iteration, until...:

>>> next(b)
0
>>> next(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

In other words, a for loop in python is actually a try-except in disguise.

As far as the concrete question goes, remember that exceptions stop normal function execution and must be dealt with separately. In Python, you should freely throw them whenever there is no point executing the rest of the code in your function, and/or none of the returns correctly reflect what happened in the function. Note that returning early from a function is different: returning early means you already figured out the answer and don't need the rest of the code to figure out the answer. I am saying that exceptions should be thrown when the answer is not known, and the rest of the code to determine the answer cannot be reasonably run. Now, "correctly reflect" itself, like which exceptions you choose to throw, is all a matter of documentation.

In the case of your particular code, I would say any situation that causes hits to be an empty list should throw. Why? Well, the way your function is setup, there is no way to determine the answer without parsing hits. So if hits is not parseable, either because the URL is bad, or because hits is empty, then the function can't answer the question, and in fact can't even really try to.

In this particular case, I would argue that even if you manage to parse and don't get a reasonable answer (alive or dead), then you should still throw. Why? Because, the function returns a boolean. Returning None is very dangerous to your client. If they do an if check on None, there won't be failure, it will just silently be treated as False. So, your client will basically always have to do an if is None check anyhow if he doesn't want silent failures... so you should probably just throw.

๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 65205505 โ€บ e-is-empty-on-exception-exception-as-e-python
e is empty on "exception Exception as e" Python - Stack Overflow
The problem is actually where you raise the exception. You aren't passing anything to exception. ... That specific exception has no __str__ method. If you look in your python installation folder in the Lib/asyncio/exceptions.py file you will ...
๐ŸŒ
DaniWeb
daniweb.com โ€บ programming โ€บ software-development โ€บ threads โ€บ 381248 โ€บ using-try-except-to-catch-a-blank-input
python - Using Try, Except to catch a blank input [SOLVED] | DaniWeb
If you are on Python 2, use raw_input() instead of input() to avoid evaluating the input (docs). Second, avoid a bare except: because it will also swallow KeyboardInterrupt; prefer catching specific exceptions (docs). A reusable pattern is: normalize user input, validate with a predicate, and loop until it passes.
๐ŸŒ
Python Land
python.land โ€บ home โ€บ language deep dives โ€บ python try except: examples and best practices
Python Try Except: Examples And Best Practices โ€ข Python Land Tutorial
January 29, 2026 - If an except clause mentions a particular class, that clause also handles any exception classes derived from that class. An empty except is equivalent to except BaseException, hence it will catch all possible exceptions.
๐ŸŒ
Real Python
realpython.com โ€บ python-raise-exception
Python's raise: Effectively Raising Exceptions in Your Code โ€“ Real Python
January 25, 2025 - In the second example, you try to access the 0 index in an empty list, and Python raises a TypeError exception for you. In this case, the error message follows the same described pattern. Even though this practice isnโ€™t an explicit convention, you should consider sticking to this pattern ...
๐ŸŒ
Derscanner
derscanner.com โ€บ vulnerability-database โ€บ Python-:-Error-handling:-empty-except-block
DerScanner Vulnerability Database: Python : Error handling: empty except block
The application contains an empty catch block, i.e. it catches an exception but does not handle it. Exception catch without its handling makes it more difficult to diagnose an error and correct it. Ignoring exceptions and other error conditions may allow an attacker to induce unexpected behavior ...