5

https://www.programiz.com/python-programming/exceptions

There is a list of exceptions in Python, and I am trying to make a list (or a set) of the exception names.

I could just simply hard code the names, but is there a way to somehow do this programmatically? Like import the exception class and get all those types of exceptions and put them a list of strings?

2
  • AFAIK: docs.python.org/3/library/exceptions.html Commented Apr 13, 2019 at 20:24
  • 1
    It may help to know what you intend to do with that list. Don't forget that imported modules and users can define their own subclasses of Exceptions. Commented Apr 13, 2019 at 20:59

1 Answer 1

4

To get list of built-in exceptions (not user-defined) you can do this:

import builtins

list_of_exception_names = [
    name for name, value in builtins.__dict__.items() 
    if isinstance(value, type) and issubclass(value, BaseException)
]
Sign up to request clarification or add additional context in comments.

3 Comments

This code will not work inside a module. __builtins__ is sometimes a dict rather than a module, in which case the __builtins__.__dict__ access fails. You should always use the builtins or __builtin__ module rather than the __builtins__ implementation detail.
@user2357112 thanks for your comments, improved my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.