简体   繁体   English

try catch 异常处理场景

[英]try catch exception handling scenario

I am looking to handle a multi-level error handling scenario, where I have a test looks somehwat like this:我正在寻找处理多级错误处理方案,我有一个测试看起来像这样:

void tester() {
    String fileName = Path.of(myDir, "file_1.lo").toString();
    assertThrows(
            Error.class,
            () -> TheCompilerClass.parent_method_called_by_testcase(fileName),
            "Expected parse error to be thrown for this test"
    );
    assertTrue(getStdErr().contains("Failed to compile"));
}

And this invokes the code I have developed where upon exception I am trying to send back something that will result in bool: True at the assertTrue statement above.这会调用我开发的代码,在出现异常时我试图发回一些会导致 bool: True 在上面的 assertTrue 语句中的东西。

My code structure is like this:我的代码结构是这样的:

parent_method_called_by_testcase() {
  try {

  } catch (Exception e) {
    System.err.println("Failed to compile ");
    //how do I return the right thing? 
    //STDERR statements can't be returned back to test case invoking methoid?
  }
}

child_method {

  //this finds that exception has occurred and should pass it up the chain
  //should this have a throw statement? or just a return?
  if (exception) {
    tell the parent so that parent can tell the testcase
  }
}

Arguably, log lines like the one you mention are not part of what is generally tested in unit tests.可以说,像您提到的那样的日志行不是单元测试中通常测试的内容的一部分。 More commonly, we test end functionality.更常见的是,我们测试终端功能。 For example, if the child method encounters a case where we throw an exception, does the parent method catch that?例如,如果子方法遇到了我们抛出异常的情况,那么父方法会捕捉到它吗? In other words, does the parent method throw an exception as well?换句话说,父方法是否也抛出异常? This is an example of an assertion that one might write in a unit test.这是一个可以在单元测试中编写的断言示例。

Here, based on your test, your, assertThrows means that you expect the parent method to throw an exception here.在这里,根据您的测试,您的assertThrows意味着您希望父方法在这里抛出异常。 So in your catch block, you would do some logging but ultimately throw e if you want the parent to throw if the child does.因此,在您的catch块中,您将进行一些记录,但如果您希望父母在孩子这样做的情况下抛出,最终会throw e

parent_method_called_by_testcase() {
  try {
    ...
  } catch (Exception e) {
    System.err.println("Failed to compile ");
    throw e;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM