The other answers all point out that you should not catch generic exceptions, but no one seems to want to tell you why, which is essential to understanding when you can break the "rule". Here is an explanation. Basically, it's so that you don't hide:

  • the fact that an error occurred
  • the specifics of the error that occurred (error hiding antipattern)

So as long as you take care to do none of those things, it's OK to catch the generic exception. For instance, you could provide information about the exception to the user another way, like:

  • Present exceptions as dialogs in a GUI
  • Transfer exceptions from a worker thread or process to the controlling thread or process in a multithreading or multiprocessing application

So how to catch the generic exception? There are several ways. If you just want the exception object, do it like this:

try:
    someFunction()
except Exception as ex:
    template = "An exception of type {0} occurred. Arguments:\n{1!r}"
    message = template.format(type(ex).__name__, ex.args)
    print(message)

Make sure message is brought to the attention of the user in a hard-to-miss way! Printing it, as shown above, may not be enough if the message is buried in lots of other messages. Failing to get the users attention is tantamount to swallowing all exceptions, and if there's one impression you should have come away with after reading the answers on this page, it's that this is not a good thing. Ending the except block with a raise statement will remedy the problem by transparently reraising the exception that was caught.

The difference between the above and using just except: without any argument is twofold:

  • A bare except: doesn't give you the exception object to inspect
  • The exceptions SystemExit, KeyboardInterrupt and GeneratorExit aren't caught by the above code, which is generally what you want. See the exception hierarchy.

If you also want the same stacktrace you get if you do not catch the exception, you can get that like this (still inside the except clause):

import traceback
print traceback.format_exc()

If you use the logging module, you can print the exception to the log (along with a message) like this:

import logging
log = logging.getLogger()
log.exception("Message for you, sir!")

If you want to dig deeper and examine the stack, look at variables etc., use the post_mortem function of the pdb module inside the except block:

import pdb
pdb.post_mortem()

I've found this last method to be invaluable when hunting down bugs.

Answer from Lauritz V. Thaulow on Stack Overflow
Top answer
1 of 16
621

The other answers all point out that you should not catch generic exceptions, but no one seems to want to tell you why, which is essential to understanding when you can break the "rule". Here is an explanation. Basically, it's so that you don't hide:

  • the fact that an error occurred
  • the specifics of the error that occurred (error hiding antipattern)

So as long as you take care to do none of those things, it's OK to catch the generic exception. For instance, you could provide information about the exception to the user another way, like:

  • Present exceptions as dialogs in a GUI
  • Transfer exceptions from a worker thread or process to the controlling thread or process in a multithreading or multiprocessing application

So how to catch the generic exception? There are several ways. If you just want the exception object, do it like this:

try:
    someFunction()
except Exception as ex:
    template = "An exception of type {0} occurred. Arguments:\n{1!r}"
    message = template.format(type(ex).__name__, ex.args)
    print(message)

Make sure message is brought to the attention of the user in a hard-to-miss way! Printing it, as shown above, may not be enough if the message is buried in lots of other messages. Failing to get the users attention is tantamount to swallowing all exceptions, and if there's one impression you should have come away with after reading the answers on this page, it's that this is not a good thing. Ending the except block with a raise statement will remedy the problem by transparently reraising the exception that was caught.

The difference between the above and using just except: without any argument is twofold:

  • A bare except: doesn't give you the exception object to inspect
  • The exceptions SystemExit, KeyboardInterrupt and GeneratorExit aren't caught by the above code, which is generally what you want. See the exception hierarchy.

If you also want the same stacktrace you get if you do not catch the exception, you can get that like this (still inside the except clause):

import traceback
print traceback.format_exc()

If you use the logging module, you can print the exception to the log (along with a message) like this:

import logging
log = logging.getLogger()
log.exception("Message for you, sir!")

If you want to dig deeper and examine the stack, look at variables etc., use the post_mortem function of the pdb module inside the except block:

import pdb
pdb.post_mortem()

I've found this last method to be invaluable when hunting down bugs.

2 of 16
167

Get the name of the class that exception object belongs:

e.__class__.__name__

and using print_exc() function will also print stack trace which is essential info for any error message.

Like this:

from traceback import print_exc

class CustomException(Exception): pass

try:
    raise CustomException("hi")
except Exception as e:
    print ('type is:', e.__class__.__name__)
    print_exc()
    # print("exception happened!")

You will get output like this:

type is: CustomException
Traceback (most recent call last):
  File "exc.py", line 7, in <module>
    raise CustomException("hi")
CustomException: hi

And after print and analysis, the code can decide not to handle exception and just execute raise:

from traceback import print_exc

class CustomException(Exception): pass

def calculate():
    raise CustomException("hi")

try:
    calculate()
except CustomException as e:
    # here do some extra steps in case of CustomException
    print('custom logic doing cleanup and more')
    # then re raise same exception
    raise

Output:

custom logic doing cleanup and more

And interpreter prints exception:

Traceback (most recent call last):
  File "test.py", line 9, in <module>
    calculate()
  File "test.py", line 6, in calculate
    raise CustomException("hi")
__main__.CustomException: hi

After raise original exception continues to propagate further up the call stack. (Beware of possible pitfall) If you raise new exception it caries new (shorter) stack trace.

from traceback import print_exc

class CustomException(Exception):
    def __init__(self, ok):
        self.ok = ok

def calculate():
    raise CustomException(False)

try:
    calculate()
except CustomException as e:
    if not e.ok:
        # Always use `raise` to rethrow exception
        # following is usually mistake, but here we want to stress this point
        raise CustomException(e.ok)
    print("handling exception")

Output:

Traceback (most recent call last):
  File "test.py", line 13, in <module>
    raise CustomException(e.message)
__main__.CustomException: hi    

Notice how traceback does not include calculate() function from line 9 which is the origin of original exception e.

🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.7 documentation
The string printed as the exception type is the name of the built-in exception that occurred. This is true for all built-in exceptions, but need not be true for user-defined exceptions (although it is a useful convention).
Discussions

Getting the exception value in Python - Stack Overflow
If I have that code: try: some_method() except Exception, e: How can I get this Exception value (string representation I mean)? More on stackoverflow.com
🌐 stackoverflow.com
python - The best way to determine exception type - Stack Overflow
I have an exception instance and need to execute code depending on it's type. Which way is more clearly - re raise exception or isinstance check? re raise: try: raise exception except More on stackoverflow.com
🌐 stackoverflow.com
June 20, 2016
Handle specific exception type in python - Stack Overflow
I have some code that handles an exception, and I want to do something specific only if it's a specific exception, and only in debug mode. So for example: try: stuff() except Exception as e: ... More on stackoverflow.com
🌐 stackoverflow.com
python - How do I find out what type of exception I am supposed to raise? - Software Engineering Stack Exchange
The top 2 answers to the following ...rowing-an-exception-in-python · At this moment (2015 March 14 Sat 2354 hrs) it seems that there's a growing consensus around the second answer (Aaron Hall's answer in case any of this changes in the future). And I think I do get the point about being specific about the type of exception ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
🌐
Python
docs.python.org › 3 › builtins › exceptions.html
Built-in Exceptions — Python 3.14.7 documentation
In Python, all exceptions must be instances of a class that derives from BaseException. In a try statement with an except clause that mentions a particular class, that clause also handles any excep...
🌐
freeCodeCamp
freecodecamp.org › news › python-print-exception-how-to-try-except-print-an-error
Python Print Exception – How to Try-Except-Print an Error
March 15, 2023 - What if you want to get the exact exception name and print it to the terminal? That’s possible too. All you need to do is use the type() function to get the type of the exception and then use the __name__ attribute to get the name of the exception.
🌐
Bobby Hadz
bobbyhadz.com › blog › python-get-type-file-line-number-of-exception
Python: Get the Type, File and Line Number of Exception | bobbyhadz
April 12, 2024 - As shown in the code sample, you can use the traceback object to get: the filename - the name of the file in which the exception occurred. the line number - on which line in the file the exception was last raised.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-print-exception
Python Print Exception - GeeksforGeeks
July 23, 2025 - This method helps us print the type of exception you caught, like <class 'ValueError'>. It's useful when we're not sure what kind of error occurred. Along with type(e), we can also print e to get the actual error message.
🌐
Real Python
realpython.com › python-exceptions
Python Exceptions: An Introduction – Real Python
March 18, 2026 - The last line of the message indicates what type of exception error you ran into. Instead of just writing exception error, Python details what type of exception error it encountered. In this case, it was a ZeroDivisionError.
Find elsewhere
🌐
LabEx
labex.io › tutorials › python-how-to-check-if-an-exception-is-of-a-certain-type-in-python-559609
How to Check If an Exception Is of a Certain Type in Python | LabEx
This is a more direct and often clearer way to handle exceptions compared to using isinstance(). When you use except ExceptionType as e:, you are telling Python to catch only exceptions that are of the type ExceptionType or a subclass of it.
🌐
Google Groups
groups.google.com › g › django-users › c › dkkXm9MIr14
How to get the Exception Type
Hi as you can see here at http://docs.python.org/tutorial/errors.html in 8.3 handling exceptions theres a piece of code that works as you want. for example try this: try: int("a") except Exception as e: #The key is using "as" and the variable name you like for retrieving the exception because if you dont you will only get #"Exception type" type print type(e) #This will give de exception type.
🌐
Python Tutorial
pythontutorial.net › home › python oop › python exception handling
Python Exception Handling in the Right Way
March 28, 2025 - To get exception information from a bare exception handler, you use the exc_info() function from the sys module. The sys.exc_info() function returns a tuple that consists of three values: type is the type of the exception occurred.
Top answer
1 of 2
2

You could store the exceptions you want to handle as keys in a dictionary with different functions as their values. Then you can catch all errors in just one except and call the dictionary to make sure the relevant function is run.

error_handler = {
                  OperationError: do_something1,
                  InvalidValue: do_something2,
                  InvalidContext: do_something2,
                  AnotherException: do_something3,
                }

try:
    #raise your exception
except (OperationError, InvalidValue, InvalidContext, AnotherException) as err:
    result = error_handlertype(err)

I suspect there might be a way to programmatically pass error_handler.keys() to except, but the means I've tried in Python2.7 have not worked so far.

Note that as martineau points out, because this uses type(err) as a dictionary key it won't handle derived exception classes the way that isinstance(err, ...) and except (err) would. You'd need to match exact exceptions.

2 of 2
1

First get rid of the except: pass clause - one should never silently pass exceptions, specially in a bare except clause (one should never use a bare except clause anyway).

This being said, the "best" way really depends on concrete use case. In your above example you clearly have different handlers for different exceptions / exceptions sets, so the obvious solution is the first one. Sometimes you do have some code that's common to all or most of the handlers and some code that's specific to one exception or exceptions subset, then you may want to use isinstance for the specific part, ie:

try:
   something_that_may_fail()
except (SomeException, SomeOtherException, YetAnotherOne) as e:
   do_something_anyway(e)
   if isinstance(e, YetAnotherOne):
      do_something_specific_to(e)

Now as mkrieger commented, having three or more exceptions to handle may be a code or design smell - the part in the try block is possibly doing too many things - but then again sometimes you don't have much choice (call to a builtin or third-part function that can fail in many different ways...).

🌐
Embedded Inventor
embeddedinventor.com › home › python exception to string
Python Exception to string
September 27, 2023 - The except clause catches the IndexError exception and prints out Exception type. On running the code, we will get the following output ... As you can see we just extracted and printed out the information about the class to which the exception ...
🌐
Tutorial Reference
tutorialreference.com › python › examples › faq › python-how-to-get-details-type-file-line-number-of-exception
How to Get Exception Information (Type, File, Line Number) in Python | Tutorial Reference
The exception object itself (the e in except Exception as e:) contains valuable information: ... type(e).__name__: Gets the name of the exception class (e.g., "ValueError", "TypeError").
Top answer
1 of 2
3

You are creating a user interface -- code is a user interface, where the "user" is another programmer, or another function. If you were the user of your code rather than the developer, what would make your code easier to use? So, look at this problem from the perspective of someone calling your function. What would be the most useful exception you could give? Note: there may be more than one answer, in which case it really doesn't matter too much. The point is, make your code as easy to use as possible.

The other important thing to remember is this: you may be only sending one exception, but your code as a whole could be sending many. The exception you throw needs to play nicely with all of the other possible exceptions (meaning: it must be distinguishable from the other exceptions).

In this specific case (and in most cases...), a generic exception isn't particularly useful. There could be more than one way that your function fails. Maybe the inputs are floats instead of integers. Maybe they are strings. Or maybe the inputs result in a divide by zero. The caller may care about these distinctions. Maybe they won't, but they might. And if not now, they might in the future.

2 of 2
1

Raising a generic xception and differentiating it just by its message would be wrong because then, if you have many of them and want to react appropriately, how would you distinguish them?

Regarding the choice of the exception, taking your example, I would say that ArithmeticError is something pretty low-level and focused on the arithmetic aspects of the problem. In your case, is it an arithmetic error the fact that 7 is not divisible by 3? No, arithmetically it's correct.

That's a problem if taken from another point of view, namely the one of your application logic, so such exception would make sense only in your application. I would make my own one (e.g. NonDivisibleTableError derived from Exception).

Now, how could that happen? That's another issue, but a quick search showed that also in Python it's possible to specify a cause when throwing an exception (see raise/from). This way you can describe what went wrong at the different levels of your application, (e.g. NonDivisibleTableError caused by some IOError), and give the user a more reasoned error message.

🌐
Python
wiki.python.org › moin › HandlingExceptions
HandlingExceptions - Python Wiki
I believe that as of 2.7, exceptions ... BaseException. However, as of Python 3, exceptions must subclass BaseException. -- ElephantJim ... You know- you can put a print d in there, and that works. But is there a better, more interesting way to get at that information that people know ...
🌐
Programiz
programiz.com › python-programming › exceptions
Python Exceptions (With Examples)
Let's learn about Python Exceptions in detail. Errors that occur at runtime (after passing the syntax test) are called exceptions or logical errors. ... Whenever these types of runtime errors occur, Python creates an exception object.
🌐
Python
docs.python.org › 3 › c-api › exceptions.html
Exception Handling — Python 3.14.7 documentation
Rather, it can be used when code needs to save and restore the exception state temporarily. Use PyErr_GetExcInfo() to read the exception state. Added in version 3.3. Changed in version 3.11: The type and traceback arguments are no longer used ...
🌐
W3Schools
w3schools.com › python › python_ref_exceptions.asp
Python Built-in Exceptions
The table below shows built-in exceptions that are usually raised in Python.