• except Exception: vs except BaseException::

    The difference between catching Exception and BaseException is that according to the exception hierarchy exception like SystemExit, KeyboardInterrupt and GeneratorExit will not be caught when using except Exception because they inherit directly from BaseException.

  • except: vs except BaseException::

    The difference between this two is mainly in python 2 (AFAIK), and it's only when using an old style class as an Exception to be raised, in this case only expression-less except clause will be able to catch the exception eg.

    class NewStyleException(Exception): pass
    
    try:
       raise NewStyleException
    except BaseException:
       print "Caught"
    
    class OldStyleException: pass
    
    try:
       raise OldStyleException
    except BaseException:
       print "BaseException caught when raising OldStyleException"
    except:
       print "Caught"
    
Answer from mouad on Stack Overflow
🌐
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 exception classes derived from that class (but not ...
Top answer
1 of 3
71
  • except Exception: vs except BaseException::

    The difference between catching Exception and BaseException is that according to the exception hierarchy exception like SystemExit, KeyboardInterrupt and GeneratorExit will not be caught when using except Exception because they inherit directly from BaseException.

  • except: vs except BaseException::

    The difference between this two is mainly in python 2 (AFAIK), and it's only when using an old style class as an Exception to be raised, in this case only expression-less except clause will be able to catch the exception eg.

    class NewStyleException(Exception): pass
    
    try:
       raise NewStyleException
    except BaseException:
       print "Caught"
    
    class OldStyleException: pass
    
    try:
       raise OldStyleException
    except BaseException:
       print "BaseException caught when raising OldStyleException"
    except:
       print "Caught"
    
2 of 3
34

If you need to catch all exceptions and do the same stuff for all, I'll suggest you this :

try:
   #stuff
except:
   # do some stuff

If you don't want to mask "special" python exceptions, use the Exception base class

try:
   #stuff
except Exception:
   # do some stuff

for some exceptions related management, catch them explicitly :

try:
   #stuff
except FirstExceptionBaseClassYouWantToCatch as exc:
   # do some stuff
except SecondExceptionBaseClassYouWantToCatch as exc:
   # do some other stuff based
except (ThirdExceptionBaseClassYouWantToCatch, FourthExceptionBaseClassYouWantToCatch) as exc:
   # do some other stuff based

The exception hierarchy from the python docs should be a usefull reading.

Discussions

python 3.x - Inheriting from BaseException vs Exception - Stack Overflow
I know what is difference between Exception and BaseException in Python. I wonder what is a good practice and more pythonic: Should my exceptions inherit from BaseException or Exception? More on stackoverflow.com
🌐 stackoverflow.com
Exception handling in python
When handing exceptions you should specify the exact exception type(s) you want to handle. Handling everything can possibility silence issues you need to fix in your code, or prevent mechanisms that rely on exceptions from working. (Like sys.exit) More on reddit.com
🌐 r/learnpython
5
5
January 25, 2022
Why is it recommended to derive from Exception instead of BaseException class in Python? - Stack Overflow
The Python 2 documentation says that "programmers are encouraged to derive new exceptions from the Exception class or one of its subclasses, and not from BaseException". Without any further explana... More on stackoverflow.com
🌐 stackoverflow.com
What is the problem with catching the base Exception class when it is needed?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
54
3
April 16, 2024
Top answer
1 of 2
50

The accepted answer is incorrect incomplete (at least for Python 3.6 and above).

By catching Exception you catch most errors - basically all the errors that any module you use might throw.

By catching BaseException, in addition to all the above exceptions, you also catch exceptions of the types SystemExit, KeyboardInterrupt, and GeneratorExit.

By catching KeyboardInterrupt, for example, you may stop your code from exiting after an initiated exit by the user (like pressing ^C in the console, or stopping launched application on some interpreters). This could be a wanted behavior (for example - to log an exit), but should be used with extreme care!

In the above example, by catching BaseException, you may cause your application to hang when you want it to exit.

2 of 2
39

Practically speaking, there is no difference between except: and except BaseException:, for any current Python release.

That's because you can't just raise any type of object as an exception. The raise statement explicitly disallows raising anything else:

[...] raise evaluates the first expression as the exception object. It must be either a subclass or an instance of BaseException.

Bold emphasis mine. This has not always been the case however, in older Python releases (2.4 and before) you could use strings as exceptions too.

The advantage then is that you get to have easy access to the caught exception. In order to be able to add as targetname, you must catch a specific class of exceptions, and only BaseException is going to do that.

You can still access the currently active exception by using sys.exc_info() though:

except:
    be = sys.exc_info()[1] 

Pick what you feel is more readable for your future self and for your colleagues.

🌐
Real Python
realpython.com › ref › builtin-exceptions › baseexception
BaseException | Python’s Built-in Exceptions – Real Python
In Python, BaseException is a built-in exception that serves as the base class for all exceptions.
🌐
Profound Academy
profound.academy › python-mid › exception-hierarchy-phonbKOpXJ362GhumAsG
Exception Hierarchy • Intermediate Python
January 20, 2025 - However, you should not use BaseException directly in your code as it is too broad and can catch any type of exception. Instead, you should use more specific exception classes that are subclasses of BaseException. Python provides a number of built-in exception classes that you can use, and ...
🌐
Python
docs.python.org › 3 › library › exceptions.html
Built-in Exceptions — Python 3.14.6 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 exception classes derived from that class (but not ...
🌐
CodeQL
codeql.github.com › codeql-query-help › python › py-catch-base-exception
Except block handles ‘BaseException’ — CodeQL query help documentation
BaseException has three important subclasses, Exception from which all errors and normal exceptions derive, KeyboardInterrupt which is raised when the user interrupts the program from the keyboard and SystemExit which is raised by the sys.exit() function to terminate the program.
Find elsewhere
Top answer
1 of 1
18

By default, all user-defined exceptions should inherit from Exception. This is recommended in the documentation:

exception Exception

All built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions should also be derived from this class.

This is also recommend by and motivated in PEP 8:

Derive exceptions from Exception rather than BaseException. Direct inheritance from BaseException is reserved for exceptions where catching them is almost always the wrong thing to do.


In general, exceptions deriving from Exception are intended to be handled by regular code. In contrast, exceptions deriving directly from BaseException are associated with special situations; handling them like normal exceptions can lead to unexpected behaviour. This is why an idiomatic "catch all" handler only handles Exception:

def retry(func):
    while True:
        try:
            return func()
        except Exception as err:
            print(f"retrying after {type(err)}: {err}")

Builtin exceptions inheriting directly from BaseException currently are KeyboardInterrupt, SystemExit, and GeneratorExit which are associated with shutdown of the program, thread or generator/coroutine. Incorrectly handling them will prevent a graceful shutdown.

Note that while the default should be to inherit from Exception, it is fine to inherit from BaseException if there is a good reason to do so. For example, asyncio.CancelledError also inherits from BaseException since it represents shutdown of asyncio's thread equivalent, the Task.

🌐
Python
docs.python.org › 3.15 › library › exceptions.html
Built-in Exceptions — Python 3.15.0rc1 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 exception classes derived from that class (but not ...
🌐
YouTube
youtube.com › mcoding
Using except: is a HUGE mistake - YouTube
Watch out for Exceptions vs BaseExceptions.We look at the difference between Python's Exception objects and BaseException objects, and we consider the use ca...
Published: June 2, 2021
Views: 53K
Top answer
1 of 1
21

Exceptions derived from BaseException are: GeneratorExit, KeyboardInterrupt, SystemExit.

According to the documentation:

  • GeneratorExit: Raised when a generator‘s close() method is called. It directly inherits from BaseException instead of StandardError since it is technically not an error.
  • KeyboardInterrupt: Raised when the user hits the interrupt key (normally Control-C or Delete). During execution, a check for interrupts is made regularly. Interrupts typed when a built-in function input() or raw_input() is waiting for input also raise this exception. The exception inherits from BaseException so as to not be accidentally caught by code that catches Exception and thus prevent the interpreter from exiting.
  • SystemExit: The exception inherits from BaseException instead of StandardError or Exception so that it is not accidentally caught by code that catches Exception. This allows the exception to properly propagate up and cause the interpreter to exit.

So the usual reasons are to prevent try ... except Exception accidently prevent interpreter exit (except GeneratorExit)

UPDATE after seeing Ashwini Chaudhary's comment:

PEP 352 - Required Superclass for Exceptions explains the reason.

With the exception hierarchy now even more important since it has a basic root, a change to the existing hierarchy is called for. As it stands now, if one wants to catch all exceptions that signal an error and do not mean the interpreter should be allowed to exit, you must specify all but two exceptions specifically in an except clause or catch the two exceptions separately and then re-raise them and have all other exceptions fall through to a bare except clause:

except (KeyboardInterrupt, SystemExit):
    raise
except:
    ...

That is needlessly explicit. This PEP proposes moving KeyboardInterrupt and SystemExit to inherit directly from BaseException.

🌐
Medium
martinxpn.medium.com › exception-hierarchy-python-58-100-days-of-python-9d8585e6569b
Exception Hierarchy Python (58/100 Days of Python) | by Martin Mirakyan | Medium
April 10, 2023 - The BaseException class is the top-level class in the exception hierarchy. It provides some common methods that all exceptions can use, such as __str__ and __repr__.
🌐
LinkedIn
linkedin.com › pulse › advanced-exception-handling-python-understanding-atexit-moonhee-lee-ezwrc
Advanced Exception Handling in Python: Understanding BaseException, atexit, and Beyond
February 28, 2024 - This article delves into the ... and cleanliness. BaseException sits at the top of Python's exception hierarchy, acting as the base class for all exceptions, including system-exiting exceptions and errors....
🌐
Python
docs.python.org › 3.3 › library › exceptions.html
5. Built-in Exceptions — Python 3.3.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 exception classes derived from that class (but not exception classes from which it is derived).
🌐
University of New Brunswick
cs.unb.ca › ~bremner › teaching › cs2613 › books › python3-doc › library › exceptions.html
Built-in Exceptions — Python 3.9.2 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 exception classes derived from that class (but not exception classes from which it is derived).
🌐
Runebook.dev
runebook.dev › en › docs › python › library › exceptions › BaseException
Understanding BaseException: The Root of Python's Error Hierarchy
The key difference is that BaseException includes exceptions that are generally used to signal program termination, like SystemExit (raised by sys.exit()) and KeyboardInterrupt (raised when a user presses Ctrl+C).
🌐
Airbrake
blog.airbrake.io › blog › python › class-hierarchy
The Python Exception Class Hierarchy
November 1, 2017 - We cannot provide a description for this page right now
🌐
Python
peps.python.org › pep-0654
PEP 654 – Exception Groups and except* | peps.python.org
For example: ExceptionGroup('issues', [ValueError('bad value'), TypeError('bad type')]). The difference between them is that ExceptionGroup can only wrap Exception subclasses while BaseExceptionGroup can wrap any BaseException subclass.