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
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ exceptions.html
Built-in Exceptions โ€” Python 3.14.2 documentation
Therefore, itโ€™s recommended to avoid subclassing multiple exception types altogether. The following exceptions are used mostly as base classes for other exceptions. ... 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.2 documentation
Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same try statement. An except clause may name multiple exceptions as a parenthesized tuple, for example: ... except (RuntimeError, TypeError, NameError): ...
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_ref_exceptions.asp
Python Built-in Exceptions
Python Functions Python Arguments Python *args / **kwargs Python Scope Python Decorators Python Lambda Python Recursion Python Generators Python Range Python Arrays Python Iterators Python Modules Python Dates Python Math Python JSON Python RegEx Python PIP Python Try...Except Python String Formatting Python None Python User Input Python VirtualEnv
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-exception-handling
Python Exception Handling - GeeksforGeeks
October 11, 2025 - Python provides four main keywords for handling exceptions: try, except, else and finally each plays a unique role. Let's see syntax: try: # Code except SomeException: # Code else: # Code finally: # Code ยท try: Runs the risky code that might ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ built-exceptions-python
Python Built-in Exceptions - GeeksforGeeks
September 5, 2025 - In Python 3: IOError is just an alias for OSError (they are the same). FileNotFoundError is a subclass of OSError, specifically raised when a file or directory does not exist. Example: This example attempts to open a missing file, which triggers FileNotFoundError (a subclass of OSError). ... try: open("non_existent_file.txt") # File does not exist except FileNotFoundError as e: # More specific print("FileNotFoundError caught:", e) except OSError as e: # General OS-related error print("OSError caught:", e)
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ exceptions
Python Exceptions (With Examples)
We can handle these built-in and ... and finally statements. Errors represent conditions such as compilation error, syntax error, error in the logical part of the code, library incompatibility, infinite recursion, etc....
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_try_except.asp
Python Try Except
You can define as many exception ... kind of error: Print one message if the try block raises a NameError and another for other errors: try: print(x) except NameError: print("Variable x is not defined") except: print("Something else went wrong") Try it Yourself ยป ยท See more Error types in our Python Built-in ...
Top answer
1 of 16
618

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.

Find elsewhere
๐ŸŒ
Real Python
realpython.com โ€บ python-exceptions
Python Exceptions: An Introduction โ€“ Real Python
December 1, 2024 - In the Python docs, you can see that there are a couple of built-in exceptions that you could raise in such a situation, for example: ... Raised when a file or directory is requested but doesnโ€™t exist. Corresponds to errno ENOENT. (Source) You want to handle the situation when Python canโ€™t find the requested file. To catch this type of exception and print it to screen, you could use the following code:
๐ŸŒ
Real Python
realpython.com โ€บ python-built-in-exceptions
Python's Built-in Exceptions: A Walkthrough With Examples โ€“ Real Python
August 1, 2024 - The IndexError and ValueError exceptions are examples of commonly used built-in exceptions in Python. In the following sections, youโ€™ll learn more about these and several other built-in exceptions.
๐ŸŒ
Dataquest
dataquest.io โ€บ blog โ€บ python-exceptions
Python Exceptions: The Ultimate Beginner's Guide (with Examples)
March 6, 2023 - The parser shows the place where the syntax error was detected by a little arrow ^. Notice also that the subsequent line print(1) was not executed since the Python interpreter stopped working when the error occurred.
๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ python-how-to-use-python-exception-types-420056
How to use Python exception types | LabEx
def divide_numbers(a, b): try: result = a / b return result except ZeroDivisionError: print("Error: Cannot divide by zero!") except TypeError: print("Error: Invalid input types!") ## Example usage print(divide_numbers(10, 2)) ## Normal division print(divide_numbers(10, 0)) ## Zero division error print(divide_numbers(10, '2')) ## Type error ยท Exceptions are crucial in Python programming because they: ... At LabEx, we emphasize the importance of understanding and effectively using exception handling to write more resilient Python applications.
๐ŸŒ
Toppr
toppr.com โ€บ guides โ€บ python-guide โ€บ tutorials โ€บ python-files โ€บ python-errors-and-built-in-exceptions
Python Errors and Built-in Exceptions | Different types of errors in Python |
October 21, 2021 - When a Python program meets an unhandled error, it terminates. A Python object that reflects an error is known as an exception. The different types of errors in Python can be broadly classified as below: Errors in syntax (Syntax Errors) Errors in logic (Logical Errors) (Exceptions)
๐ŸŒ
Tutorial Teacher
tutorialsteacher.com โ€บ python โ€บ error-types-in-python
Error Types in Python
The following table lists important built-in exceptions in Python. The IndexError is thrown when trying to access an item at an invalid index. ... >>> L1=[1,2,3] >>> L1[3] Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> L1[3] IndexError: list index out of range ยท The ModuleNotFoundError is thrown when a module could not be found. ... >>> import notamodule Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> import notamodule ModuleNotFoundError: No module named 'notamodule'
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ exception-handling-python
Exception & Error Handling in Python | Tutorial by DataCamp | DataCamp
December 12, 2024 - Instead of throwing the exception and terminating the program, it will display the error message we provided. value = 2_000 try: if value > 1_000: # raise the ValueError raise ValueError("Please add a value lower than 1,000") else: print("Congratulations! You are the winner!!") # if false then raise the value error except ValueError as e: print(e) This type of exception handling helps us prepare for errors not covered by Python and are specific to your application requirement.
๐ŸŒ
WsCube Tech
wscubetech.com โ€บ resources โ€บ python โ€บ exception-handling
Exception Handling in Python: All Types With Examples
October 1, 2025 - Learn Python Exception Handling with examples, types, pros & cons. Understand how to manage errors effectively in Python for better code readability.
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ python โ€บ python_exceptions.htm
Python - Exceptions Handling
The final argument, trace back, is also optional (and rarely used in practice), and if present, is the traceback object used for the exception. An exception can be a string, a class or an object. Most of the exceptions that the Python core raises are classes, with an argument that is an instance ...
๐ŸŒ
Runestone Academy
runestone.academy โ€บ ns โ€บ books โ€บ published โ€บ fopp โ€บ Exceptions โ€บ standard-exceptions.html
19.4. Standard Exceptions โ€” Foundations of Python Programming
The classes that define the objects are organized in a hierarchy, which is shown below. This is important because the parent class of a set of related exceptions will catch all exception messages for itself and its child exceptions. For example, an ArithmeticError exception will catch itself and all FloatingPointError, OverflowError, and ZeroDivisionError exceptions. BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- StopIteration +-- StopAsyncIteration +-- ArithmeticError | +-- FloatingPointError | +-- OverflowError | +-- ZeroDivisionError +-- AssertionErro
๐ŸŒ
LearnPython.com
learnpython.com โ€บ blog โ€บ python-exceptions
A Brief Guide to Python Exceptions | LearnPython.com
If you run into this Python exception, the solution is to search for syntax errors in your code and fix them. This exception indicates that you tried to perform an operation using the wrong data type. As the following example demonstrates, you cannot โ€œaddโ€ a number and a string: value = 5 name = 'John' print(value + name) # TypeError: unsupported operand type(s) for +: 'int' and 'str' This exception often appears when you try to perform an operation with a None value โ€“ which is a type that accepts no operations.