Python:Java 在 python 中抛出等效项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18289352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python : Java throws equivalent in python
提问by Nikhil Rupanawar
Not attempting to compare the languages but just for knowledge,
不是试图比较语言,而是为了知识,
Is there any way to have equivalent of java throws
keyword/functionality in Python?
有什么方法可以throws
在 Python 中获得相当于 java关键字/功能的方法吗?
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:
Python:
@someDecorator # any way to do?
def someMethod():
pass
采纳答案by Eric
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:
如果不能有静态类型参数,就不能有静态 throws 声明。例如,我无法注释这个函数:
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
回答by arshajii
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.
据我所知,Python 中没有标准的等价物,也没有必要。您能做的最好的事情是在文档字符串中指出在什么情况下会引发什么异常/错误,并将其留给使用您的函数的人来解决其余问题。
In Java, the throws clause is a sort of bookkeeping. For example,
在 Java 中,throws 子句是一种簿记。例如,
try {
foo();
} catch (IOException ioe) {
}
doesn't compile unless foo
is known to have the potential of throwing an IOException
. The analog in Python:
除非foo
已知有可能抛出IOException
. Python 中的模拟:
try:
foo()
except IOError as ioe:
pass
compiles regardless. There is no concept of "checked vs unchecked".
编译不管。没有“检查与未检查”的概念。