Dawn17
Dawn17

Reputation: 8297

How do we get the list of exceptions in Python programmatically?

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?

Upvotes: 5

Views: 539

Answers (1)

sanyassh
sanyassh

Reputation: 8550

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)
]

Upvotes: 4

Related Questions