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
Discussions

Python empty list Exception - Stack Overflow
I have this function: def foo(): a = [] if not a: print "empty" return None else: print "not empty" return a Is there any Exception that do the same? Ju... More on stackoverflow.com
🌐 stackoverflow.com
How to catch empty user input using a try and except in python? - Stack Overflow
I am trying to figure out how I can catch empty user input using a try and except. If you had this for example: try: #user input here. integer input except ValueError: #print statement sa... More on stackoverflow.com
🌐 stackoverflow.com
python - Why can I not catch a Queue.Empty exception from a multiprocessing Queue? - Stack Overflow
It means you should expect the ... exceptions raised are the same unless specified otherwise. And Queue.Queue documents when it raises Queue.Empty. 2012-12-20T15:27:48.513Z+00:00 ... Blckknght's answer from back in 2012 is still correct, however using Python 3.7.1 I discovered ... More on stackoverflow.com
🌐 stackoverflow.com
python - When and how should I use exceptions? - Software Engineering Stack Exchange
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. ... That's a really confusing way to check for an empty list. More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
🌐
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 - Why should you, and how can you improve code like the example above? All exceptions, including system exceptions, inherit from a class called BaseException. 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.
🌐
CodeQL
codeql.github.com › codeql-query-help › python › py-empty-except
Empty except — CodeQL query help documentation
An empty except block may be an indication that the programmer intended to handle the exception, but never wrote the code to do so. Ensure all exceptions are handled correctly. In this example, the program keeps running with the same privileges if it fails to drop to lower privileges.
🌐
Java2s
java2s.com › example › python-book › catching-all-the-empty-except-and-exception.html
Python - Catching all: The empty except and Exception
Python · Exception · try/except/else Statement · To have a general "catchall" clause, an empty except does the trick: try: action() except NameError: ... # Handle NameError except IndexError: ... # Handle IndexError except: ... # Handle all other exceptions else: ...
🌐
Firas
firas.io › posts › python exception handling
Python Exception Handling | Firas Sadiyah
February 25, 2024 - The second strategy is to make the pipeline function fail graciously if it receives an empty dataframe from any of the mini-functions by using 1) a custom exception and 2) a try-except block. A custom exception is a user-defined class that inherits from the base Exception class and allows us to create our own type of exception. For example, we can create a custom exception called EmptyDataFrameException as follows:
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 is used to pop one element at a time.
🌐
Python
docs.python.org › 3 › library › exceptions.html
Built-in Exceptions — Python 3.14.5rc1 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 arguments.
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.

🌐
CSDN
devpress.csdn.net › python › 62fd99cdc677032930804062.html
Python: Queue.Empty Exception Handling - DevPress官方社区
August 18, 2022 - After a short debate with someone about exception handling in Python - sparked by the handling of a queue object - I thought I'd throw it out there... import Queue q = Queue.Queue() try: task=q.get(False) #Opt 1: Handle task here and call q.task_done() except Queue.Empty: #Handle empty queue here pass #Opt2: Handle task here and call q.task_done()
🌐
Reddit
reddit.com › r/pythontips › catch on empty queue
r/pythontips on Reddit: catch on empty queue
March 1, 2023 -

I am trying to update a variable inside another thread by using a queue, but I'm unsure of how to handle it if its empty. If I try to access it when its empty, my app freezes, and i dont know what the type is, so I cant do an if expression. If I print an empty queue, it outputs nothing - not even a new line.

Edit: Solved, thank you for your help in the comments, my app in now working perfectly! (queue.Empty())

🌐
Iditect
iditect.com › faq › python › tryexcept-clause-with-an-empty-except-code-in-python.html
Try-except clause with an empty except code in python
However, there might be rare cases ... If you do decide to use an empty except clause, you should include comments explaining why you're using it and what the rationale is. This can help other developers understand your intention. Here's an example of using an empty except clause ...
🌐
Python
bugs.python.org › issue40097
Issue 40097: Queue.Empty issue - Python3.8 - Python tracker
This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/84278
🌐
Python
docs.python.org › 3.13 › library › exceptions.html
Built-in Exceptions — Python 3.13.3 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 arguments.
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.5rc1 documentation
The last line of the error message indicates what happened. Exceptions come in different types, and the type is printed as part of the message: the types in the example are ZeroDivisionError, NameError and TypeError. The string printed as the exception type is the name of the built-in exception that occurred.
🌐
GitHub
github.com › crossbario › autobahn-python › issues › 539
Error happens when callee raise an empty Exception · Issue #539 · crossbario/autobahn-python
November 1, 2015 - """ @asyncio.coroutine def onJoin(self, ... # raise empty exception raise Exception() yield from self.register(sqrt, u'com.myapp.sqrt') try: yield from self.call('com.myapp.sqrt') except: print('exception catch') if __name__ == '__main__': runner = ApplicationRunner( u"ws://f1:8080/ws", u"crossbardemo", debug_wamp=False, # optional; log many WAMP details debug=False, # optional; log even more details ) runner.run(Component) ... C:\Anaconda3\python.exe ...
Author   tangyouze