[英]Java: Unreported exception Exception; must be caught or declared to be thrown
I get this error:我收到此错误:
/student/src/reflection/tester/TestRunnerTests.java:21: error: unreported exception Exception; must be caught or declared to be thrown testRunner.runTests(testClassNames);
So it shows that the error must be on testRunner.runTests(testClassNames);
所以它表明错误必须在
testRunner.runTests(testClassNames);
line in this class:此 class 中的行:
public class TestRunnerTests {
@Test
public void runsTestsFromDecoupledFiles() throws Exception {
List<String> testClassNames = List.of(
"reflection.tester.ExampleTests1", "reflection.tester.ExampleTests2");
TestRunner testRunner = new TestRunner();
testRunner.runTests(testClassNames);
String result = testRunner.getResult();
assertThat(result, containsString("test1() - OK"));
assertThat(result, containsString("test2() - FAILED"));
assertThat(result, containsString("test3() - OK"));
assertThat(result, containsString("test4() - FAILED"));
assertThat(result, containsString("test5() - OK"));
assertThat(result, containsString("test6() - FAILED"));
assertThat(result, not(containsString("helperMethod()")));
}
}
My actual code looks like this:我的实际代码如下所示:
public class TestRunner{
List<String> result = new LinkedList<>();
List<String> annotatedMethods = new LinkedList<>();
public void runTests(List<String> testClassNames) throws Exception {
for (String test: testClassNames) {
Class<?> aClass = Class.forName(test);
getClassMethods(aClass);
}
}
.....
}
Tried something like this, but it says A catch statement that catches an exception only to wrap it in a new instance of the same type of exception and throw it should be avoided
尝试过这样的事情,但它说
A catch statement that catches an exception only to wrap it in a new instance of the same type of exception and throw it should be avoided
try{
for (String test: testClassNames) {
Class<?> aClass = Class.forName(test);
getClassMethods(aClass);
}
} catch (Exception e){
throw new Exception(e);
}
How should I solve it?我该如何解决?
If you throw an Exeption you have to catch it anywhere.如果你抛出异常,你必须在任何地方抓住它。 So you need to wrap the call of the method "runTests" into a try-catch
因此,您需要将方法“runTests”的调用包装到 try-catch
(General: You need to catch a thrown exception outside of this instance) (一般:您需要在此实例之外捕获抛出的异常)
you wrote: testRunner.runTests(testClassNames);
你写道:
testRunner.runTests(testClassNames);
try: try{testRunner.runTests(testClassNames);} catch (Exception e) {...}
尝试:
try{testRunner.runTests(testClassNames);} catch (Exception e) {...}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.