【问题标题】:Java: Unreported exception Exception; must be caught or declared to be thrownJava:未报告的异常异常;必须被抓住或宣布被扔掉
【发布时间】:2021-04-26 07:10:02
【问题描述】:

我收到此错误:

/student/src/reflection/tester/TestRunnerTests.java:21: error: unreported exception Exception; must be caught or declared to be thrown testRunner.runTests(testClassNames);

所以它表明错误必须在这个类的testRunner.runTests(testClassNames);行:

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()")));
    }
}

我的实际代码如下所示:

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);
       }
   }
.....
} 

试过这样的东西,但它说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);
}

我该如何解决?

【问题讨论】:

标签: java exception


【解决方案1】:

如果你抛出异常,你必须在任何地方接住它。所以你需要将方法“runTests”的调用包装成一个try-catch

(一般:您需要在此实例之外捕获抛出的异常)

你写道: testRunner.runTests(testClassNames);

尝试: try{testRunner.runTests(testClassNames);} catch (Exception e) {...}

【讨论】:

  • 我在上面试过了,但还是不行:/
  • 不,你没有尝试,如果我在你写的第一个代码 sn-p 中看对了:testRunner.runTests(testClassNames);try:try{testRunner.runTests(testClassNames);} catch (Exception e) {...}
  • 当你尝试它时,你只是抛出了一个新异常:throw new Exception(e); 但是你需要在这个实例之外的任何地方捕获这个异常,不要抛出一个新的异常,要么什么都不写,要么做点什么,但不要抛出新的异常
  • 如果您遇到更多问题,请告诉我
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多