Python : Java throws equivalent in python

Nikhil Rupanawar picture Nikhil Rupanawar · Aug 17, 2013 · Viewed 15.3k times · Source

Not attempting to compare the languages but just for knowledge,

Is there any way to have equivalent of java throws keyword/functionality in Python?

or the way we can recognize checked exception thrown by any method at static time?

or Passing(chaining) exception handling responsibility?

Java:

public void someMethod() throws SomeException
{

}

Python:

@someDecorator  # any way to do?
def someMethod():
    pass

Answer

Eric picture Eric · Aug 17, 2013

If you can't have statically typed arguments, you can't have static throws declarations. For instance, there's no way for me to annotate this function:

def throw_me(x):
    raise x

Or even this one:

def call_func(f):
    f()  # f could throw any exception

What you can do is make it an error to throw any type of exception other than those specified:

from functools import wraps

class InvalidRaiseException(Exception):
    pass

def only_throws(E):
    def decorator(f):
        @wraps(f)
        def wrapped(*args, **kwargs):
            try:
                return f(*args, **kwargs)
            except E:
                raise
            except InvalidRaiseException:
                raise
            except Exception as e:
                raise InvalidRaiseException("got %s, expected %s, from %s" % (
                    e.__class__.__name__, E.__name__, f.__name__)
                )

        return wrapped
    return decorator
@only_throws(ValueError)
def func(x):
    if x == 1:
        raise ValueError
    elif x == 2:
        raise Exception
>>> func(0)
>>> func(1)
ValueError
>>> func(2)
InvalidRaiseException: got Exception, expected ValueError, from func