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?


public void someMethod() throws SomeException



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

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

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

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

There is no standard equivalent of this in Python as far as I know, and it’s not necessary either. The best you can do is indicate in the docstring what exceptions/errors are raised in what circumstances, and leave it to whoever is using your functions to work out the rest.

In Java, the throws clause is a sort of bookkeeping. For example,

try {
} catch (IOException ioe) {


doesn’t compile unless foo is known to have the potential of throwing an IOException. The analog in Python:

except IOError as ioe:

compiles regardless. There is no concept of “checked vs unchecked”.

As an addition:

Python introduced Type-Hints for documentation purpose in PEP 484:

def foo(bar: str) -> int:

As answered in Python type hinting with exceptions and there is currently no way to define the Exceptiones which are raised by a function.