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 โ€บ builtins โ€บ exceptions.html
Built-in Exceptions โ€” Python 3.14.7 documentation
The path to any file which triggered the exception. Changed in version 3.3: Added the name and path attributes. ... A subclass of ImportError which is raised by import when a module could not be located. It is also raised when None is found in sys.modules. Added in version 3.6. ... Raised when a sequence subscript is out of range. (Slice indices are silently truncated to fall in the allowed range; if an index is not an integer, TypeError is raised.)
๐ŸŒ
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.
Discussions

How to distinguish between two different requests.exceptions.ConnectionError types?

Starting from the basic skeleton of:

import sys

try:
    # client code
except requests.exceptions.ConnectionError as error:
    sys.exc_info()

What sys.exc_info gives you is a tuple that will look like: 'Connection aborted'; the error instance; and a traceback if applicable, but for requests.exceptions.ConnectionError, since it turns out to be a built-in exception that has some special rules, there's no third element in this instance.

From here, you should be able to compare on type(sys.exc_info()[1]) to either PermissionError or ConnectionError:

type(sys.exc_info()[1]) is PermissionError

and handle based on that. It's a little under-the-hood, so preferably keep this isolated in a dark cellar that doesn't need to be entered often. :P Hope this helps! I can't test it fully on my local since I don't use Docker these days, but I managed to get up to the type call, so hopefully any finnickiness with the type comparison is fairly simple to figure out.

More on reddit.com
๐ŸŒ r/Python
6
3
June 10, 2018
While loop TypeError: unorderable types: NoneType() > int()

list.append(x) is a method that changes the list in-place and returns the value of None rather than the list itself.

> L = []
> L.append(123) is None
True
> L == [123]
True

So in line 19, when you set y = current_chain.append(y), you're setting y to be None.

More on reddit.com
๐ŸŒ r/learnpython
9
2
August 12, 2015
๐ŸŒ
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....
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ tutorial โ€บ errors.html
8. Errors and Exceptions โ€” Python 3.14.7 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, for example: ... except RuntimeError, TypeError, NameError: ...
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ exception-handling-python
Exception & Error Handling in Python | Tutorial by DataCamp | DataCamp
May 29, 2026 - 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.
๐ŸŒ
Tutorial Teacher
tutorialsteacher.com โ€บ python โ€บ error-types-in-python
Error Types in Python
Learn about built-in error types in Python such as IndexError, NameError, KeyError, ImportError, etc.
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.

Find elsewhere
๐ŸŒ
Dataquest
dataquest.io โ€บ home โ€บ blog โ€บ python exceptions: the ultimate beginner's guide (with examples)
Python Exceptions: The Ultimate Beginner's Guide (with Examples)
March 6, 2023 - When an unexpected condition is encountered while running a Python code, the program stops its execution and throws an error. There are basically two types of errors in Python: syntax errors ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ built-exceptions-python
Python Built-in Exceptions - GeeksforGeeks
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)
Published: April 18, 2026
๐ŸŒ
Scientech Easy
scientecheasy.com โ€บ home โ€บ blog โ€บ types of exception in python
Types of Exception in Python - Scientech Easy
January 29, 2026 - Learn types of exception in Python: standard built-in exception, user-defined exception. Python has a rich hierarchy of exception classes
๐ŸŒ
Sentry
blog.sentry.io โ€บ practical-tips-on-handling-errors-and-exceptions-in-python
Guide to Errors vs Exceptions in Python | Sentry Blog
April 1, 2025 - When Python encounters an exception at runtime, it generates an exception object containing: The type of exception, for example, ZeroDivisionError. A description of what went wrong, for example, division by zero. The traceback, which shows exactly where the exception occurred in the code.
๐ŸŒ
C# Corner
c-sharpcorner.com โ€บ article โ€บ type-of-exception-in-python
Types Of Exceptions In Python
March 22, 2020 - The finally block is used to execute code, irrespective of the result of the try and except blocks. When an error occurs, or exception as we call it, Python will generally stop and generate a mistake message. The exception is handled using the try statement. ... The try block will generate an error because 10 was not divided by 0. The try block is an error so, the except block will be executed. Without the try block, the program will show the error in the output screen.
๐ŸŒ
Real Python
realpython.com โ€บ python-built-in-exceptions
Python's Built-in Exceptions: A Walkthrough With Examples โ€“ Real Python
March 18, 2026 - 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.
๐ŸŒ
WsCube Tech
wscubetech.com โ€บ resources โ€บ python โ€บ exception-handling
Exception Handling in Python: All Types With Examples
August 6, 2026 - Explore Python exception handling with examples. Learn exception handling, types of exceptions & the advantages & disadvantages of exception handling. Read now.
๐ŸŒ
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)
๐ŸŒ
Real Python
realpython.com โ€บ python-exceptions
Python Exceptions: An Introduction โ€“ Real Python
March 18, 2026 - 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:
๐ŸŒ
Learn Python
learnpython.dev โ€บ 03-intermediate-python โ€บ 40-exceptions โ€บ 10-all-about-exceptions
All About Exceptions :: Learn Python by Nina Zakharenko
An important thing to know is that exceptions, like everything else in Python, are just objects. They follow an inheritance hierarchy, just like classes do. For example, the ZeroDivisionError is a subclass of ArithmeticError, which is a subclass of Exception, itself a subclass of BaseException.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-exception-handling
Python Exception Handling - GeeksforGeeks
The try block contains code that may fail and except block catches the error, printing a safe message instead of stopping the program. Python provides four main keywords for handling exceptions: try, except, else and finally each plays a unique role.
Published: May 29, 2026
๐ŸŒ
Honeybadger
honeybadger.io โ€บ blog โ€บ a-guide-to-exception-handling-in-python
The ultimate guide to Python exception handling - Honeybadger Developer Blog
March 28, 2025 - Exceptions can occur for various ... conditions. Examples of exceptions in Python include ZeroDivisionError, TypeError, FileNotFoundError, and ValueError, among others....
๐ŸŒ
Coddy.Tech
coddy.tech โ€บ learn โ€บ courses โ€บ exception handling in python โ€บ types of exceptions
Types of Exceptions โ€“ Exception Handling in Python | Coddy
Lesson 10 of 16 in Coddy's Exception Handling in Python course. ... These Exceptions are already available in python. ex. EOFError, IndexError, TypeError, ValueError etc