Java 7 accurate recovery code and legacy code

The more precisely rethrow allows you to write code that throws an exception that is really thrown:

public void foo(String bar) throws FirstException, SecondException { try{ // Code that may throw both FirstException and SecondException } catch (Exception e){ throw e; } } 

Before Java 7, you had to write:

  public void foo(String bar) throws Exception { try{ // Code that may throw both FirstException and SecondException } catch (Exception e){ throw e; } } 

My question is : is there a tool that can detect an inaccurate throw to replace " Exception " with " FirstException, SecondException "?

So far I have verified that there is no compiler in Eclipse. FindBugs or CodePro has no rule.

+6
source share
2 answers

I think this is not a situation for warning the compiler, because an β€œoverly wide” exception is not necessarily a problem: if this method is not final or private, it determines which exception any implementation of the subclass can implement. In this case, wide coverage may be intentional.

Your question will apply equally well for Java pre-7:

 public void foo(String bar) throws Exception { // Code that may throw both FirstException and SecondException } 

Here throws Exception can also be considered bad practice (but there are no warnings about this).

On the same line of the argument, note that you will receive a compilation error when you try to catch an excluded (marked) exception that cannot be executed, but you can add all kinds of exceptions that the implementation body does not use in the throws .

A tool like FindBugs would be helpful.


Update: β€œIf this method is not final or private”: I must agree that there may also be a warning for private or final methods (and possibly static).

Update 2: even for the final methods, you can leave your possibilities open in order to throw more exceptions in the future without breaking the interface.

+1
source

Try to make an exception before the throw, maybe he will perform the trick?

 public void foo(String bar) throws FirstException, SecondException { try{ // Code that may throw both FirstException and SecondException } catch (Exception e){ throw ((e instanceof FirstException) ? (FirstException)e : (SecondException)e); } } 

By the way, repeating the same exception seems rather awkward to me ...

-2
source

Source: https://habr.com/ru/post/901195/


All Articles