这种Java异常风格是不是很糟糕的做法?

Geo*_*Geo 8 java coding-style exception

在一个方法中进行多次尝试并构造这样的代码是不是被认为是不好的做法?

public void whatever() {
   try {
     methodThatMayThrowIOException();
   } catch(IOException io) {
     // do something with exception here
   }

   // do more stuff here that won't throw exceptions

   try {
     methodThatMayThrowCustomException();
   } catch(CustomException ce) {
     // do something with custom exception here
   }
}
Run Code Online (Sandbox Code Playgroud)

Adr*_*der 7

如果该方法可以继续执行,即使发生指定的异常也没有任何问题,这应该没问题.

如果异常应该导致方法中的问题进一步发生问题,我会让它冒出来.


Alb*_*gni 5

不,这不对.当它们被抛出时捕获特定异常是一个很好的观点,它肯定比这更好:

public void whatever {
    try {
        methodThatMayThrowIOException();
        // do more stuff here that won't throw exceptions
        methodThatMayThrowCustomException();
    } catch(ParentException e) {
        // do something with custom exception here
    }
}
Run Code Online (Sandbox Code Playgroud)


Dan*_*ark 3

您的代码读起来就像它一样,因为您想要执行第 1 部分(并解析,IOException必要时进行捕获),执行无异常部分,然后执行methodThatMayThrowCustomException. 您的代码实际上无法以任何其他方式编写并保留相同的功能。这是夸张的说法,但任何其他版本在表面意义上都会有所不同。

一样:

public void whatever {
   try {
     methodThatMayThrowIOException();
     // do more stuff here that won't throw exceptions
     methodThatMayThrowCustomException();
   } catch(IOException io) {
     // do something with io exception here
   } catch(CustomException ce) {
     // do something with custom exception here
   }
}
Run Code Online (Sandbox Code Playgroud)

如果抛出任何异常,它的执行方式也完全不同。如果您需要按顺序从第 1 部分恢复,无论如何都要点击第 2 部分,然后继续第 3 部分,您实际上无法以任何其他方式编写代码。

使用两个 catch 块并没有什么问题,但将导致 IOException 的内容与引发 CustomException 的内容混合在一起可能会导致问题混合,从而使代码难以理解。但事实上,它不仅有效,而且是做你正在做的事情的唯一方法。