我有运行测试的命令行工具。有测试运行器类,它在测试执行之前做了一些准备,然后运行测试并进行报告。如果我的类捕获异常并向上层抛出新的自定义异常,然后上层也将它抛出到上层(直到View类,它将显示/记录异常),这样可以吗?
class Program
{
static void Main(string[] args)
{
testRunner = new TestRunner();
try
{
testRunner.RunTest();
testRunner.GetReport();
}
catch (TestRunnerException ex)
{
Print(ex); // prints nicely two levels of exceptions for user
Log(ex); // writes to file all levels of exceptions
}
}
}
class TestRunner
{
void RunTest()
{
// run test here
}
TestReport GetTestReport()
{
try
{
return testReporter.GenerateReport();
}
catch (Exception ex)
{
throw new TestRunnerException("Failed to generate report.", ex);
}
}
}
class TestReporter
{
TestReport GenerateReport()
{
try
{
// create report here
}
catch (Exception ex)
{
throw new ReportException($"Test '{testName}' missing data.", ex)
}
}
}
它不是从catch
抛出自定义异常,而是捕获所有异常,这是一个不好的做法;想像:
TestReport GetTestReport() {
// throws NullReferenceException (yes, GenerateReport() has a bug)
return testReporter.GenerateReport();
}
catch (Exception ex) {
// Bad Practice: here we hide hideous NullReferenceException,
// but throw innocent TestRunnerException
throw new TestRunnerException("Failed to generate report.", ex);
}
...
try {
GetTestReport();
}
catch (TestRunnerException ex) {
// Nothing serious: Tests report fails, let's do nothing
// Under the hood: the routine went very wrong -
// NullReferenceException - in GenerateReport();
;
}
我建议在catch
中使用特定的例外:
TestReport GetTestReport() {
// throws NullReferenceException
return testReporter.GenerateReport();
}
catch (NotAuthorizedException ex) {
// We are not allowed to run tests only, nothing serious
throw new TestRunnerException("Failed to generate report. Not authorized", ex);
}
...
try {
GetTestReport();
}
catch (TestRunnerException ex) {
// Nothing serious: Tests report fails, let's do nothing
;
}