java 测试一个方法是否会在不调用它的情况下抛出异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6778637/
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
Test a method if it would throw an exception or not without invoking it
提问by Eng.Fouad
How can I test whether a given method will throw an exception or not (depending on the passed object) without invoking it?
如何在不调用的情况下测试给定方法是否会引发异常(取决于传递的对象)?
For example:
例如:
public static boolean isAllowed(SomeObject obj)
{
try
{
myMethod(obj);
return true;
}
catch(Exception ex)
{
return false;
}
}
but the above method will perform MyMethod()
, how can I achieve this in java?
但是上面的方法会执行MyMethod()
,我怎样才能在java中实现呢?
EDIT:
编辑:
Actually, I want to do this to validate a filename. see this: Validate a file name on Windows
实际上,我想这样做来验证文件名。请参阅:在 Windows 上验证文件名
回答by stefan
As others have said, it is in general impossible to tell whether an exception will be thrown based on the input without actually computing it. Java is turing complete, so this is reducible to the halting problem. However, you can find all exceptions that a method can throwat runtime:
正如其他人所说,通常不可能在不实际计算的情况下根据输入判断是否会抛出异常。Java 是图灵完备的,所以这可以归结为停机问题。但是,您可以找到方法在运行时可能抛出的所有异常:
try {
Method myMethod = this.getClass().getMethod("myMethod");
System.out.println(Arrays.toString(myMethod.getExceptionTypes()));
} catch (NoSuchMethodException e) {}
回答by Andy Thomas
You can provide a sibling method isAllowed() that tests explicitly for the conditions that result in the exception.
您可以提供一个兄弟方法 isAllowed() 来显式测试导致异常的条件。
Risk of error exists. The two methods need to keep synchronized the conditions leading to an exception. However, frequently it is feasible to write the test method correctly.
存在错误风险。这两种方法需要保持同步导致异常的条件。但是,正确编写测试方法通常是可行的。
From Joshua Bloch's "Effective Java":
来自 Joshua Bloch 的“Effective Java”:
A class with a "state-dependent" method that can be invoked only under certain unpredictable conditions should generally have a separate "state-testing" method indicating whether it is appropriate to invoke the state-dependent method.
具有只能在某些不可预测的条件下调用的“状态相关”方法的类通常应该具有单独的“状态测试”方法,指示是否适合调用状态相关方法。
回答by Edward Loper
In the general case, you can't. For example, the method in question might use a random number generator to decide whether to throw an exception or not. Or for a more realistic example, if the method in question tries to open a file, then you can't know in advance whether some other process might delete that file just before you try to open it (which would cause an exception).
在一般情况下,你不能。例如,所讨论的方法可能使用随机数生成器来决定是否抛出异常。或者举一个更现实的例子,如果有问题的方法试图打开一个文件,那么你无法提前知道其他进程是否会在你尝试打开它之前删除该文件(这会导致异常)。
Java tells you whether it mightthrow an exception at compile time (w/ throws declarations), but you can't determine whether it actually will throw an exception without executing it.
Java 会告诉您它是否会在编译时抛出异常(带有 throws 声明),但您无法确定它是否真的会在不执行的情况下抛出异常。
回答by iammilind
You cannot know at compile time if the method will throw an exception at runtime or not.
您无法在编译时知道该方法是否会在运行时抛出异常。
If you want to know if the method can throw exception; just don't enclose that method in try-catch
block. Editor like ecliple will clearly show a compilation error, if the method was throwing an exception.
如果您想知道该方法是否可以抛出异常;只是不要将该方法包含在try-catch
块中。如果方法抛出异常,像 ecliple 这样的编辑器会清楚地显示编译错误。
This is what you want; or I misunderstood your question.
这就是你想要的;或者我误解了你的问题。
回答by alphazero
Clearly if you don't want to invoke but need to understand behavior if invoked, then you need to read the method byte codes.
显然,如果您不想调用但需要了解调用时的行为,那么您需要阅读方法字节码。
Another option is to provide a mock-classloader and load mock classes (and thus no-op method implementations).
另一种选择是提供一个模拟类加载器并加载模拟类(从而实现无操作方法)。
In a fully functional universe, the above would be a reasonable approach. Given it is Java, the question of how you guarantee and measure side-effects remains to be answered. Perhaps the above will work for your specific case, but for the general case you are effectively asking for static analysis of Java bytecodes and that is probably an entire domain of study in its own right.
在一个功能齐全的宇宙中,上述方法是一种合理的方法。鉴于它是 Java,您如何保证和衡量副作用的问题仍有待回答。也许上述内容适用于您的特定情况,但对于一般情况,您实际上是在要求对 Java 字节码进行静态分析,这本身可能是一个完整的研究领域。
回答by Paul
It's better to understand the methods and the valid parameters than to blindly test methods before calling (which is not possible).
与其在调用之前盲目地测试方法(这是不可能的),不如了解方法和有效参数。
Validate your parameters before passing them to the method. Here's a trivial illustration where passing null would cause an exception:
在将参数传递给方法之前验证它们。这是一个简单的说明,其中传递 null 会导致异常:
int getLength(String s)
{
return s.length();
}
void someMethod()
{
int len = -1;
if (myString != null)
len = getLength(myString);
}