简体   繁体   中英

Raising a "null" exception in Python

I am trying to write a function that does error checking in the following way.

def check_var_type(var, var_name, type):
    t = type(var)
    if t is type or t is list:
        return None
    else:
        return TypeError(
            f"Invalid {var_name} type '{t.__module__}.{t.__name__}', "
            f"'{float.__module__}.{float.__name__}' or "
            f"'{list.__module__}.{list.__name__}' expected.")


my_var = 1
raise check(my_var, 'my_var', float)

My expectation of Python's raise command was that if I pass None to it, it would simply ignore it and raise no exception. The response, however, was:

TypeError: exceptions must derive from BaseException

I then had a look at Python's built-in exception types to see if something like Nonthing , NoError , etc. exists. No luck though.

I can, of course raise the exception in the check_var_type function, but I don't want to, since this would add an extra line to the stack trace.

So, my (perhaps silly) question is: How can I use raise to not raise an exception? :-)

Thanks

If you don't want to raise an exception, don't call raise (whose sole job IS to raise an exception).

Perhaps what you really want is to call raise from inside check_var_type when you actually do want to raise an exception, and just use return when you don't.

An alternative might be to leave check_var_type as is, but wrap the call to it in an if that one raises the exception returned when an exception is returned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM