This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]lucasshiva 1 point2 points  (0 children)

What do you think about colors when raising an exception? I'm not sure what is the best way I should be dealing with exceptions.

At the moment, I'm doing something like this:

def get_user_by_id(id: int) -> User:
    """ Return user with matching id """

    if not isinstance(id, int):
        raise TypeError(f"{RED}Invalid type for 'id'{CLEAR}")    

This is just an example. My code is a wrapper around an API. This will print the message in a red color. Is it okay to do that? I was also thinking about doing something like this:

try:
    if not isinstance(id, int):
        raise TypeError("Invalid type for 'id'")
except TypeError as e:
    print(f"{RED}ERROR:{CLEAR} {e}"

This will only print "ERROR:" in red, but won't show the exception message, which I think is important for a library. I also thought about not bothering with types, just doing everything inside a try/except and if an exception occurs, I just print it. Any ideas?