Is “throws Throwable” good practice

前端 未结 9 1106
攒了一身酷
攒了一身酷 2020-12-30 21:14

In the past I\'d read tons of code with methods like:

public Object doSomething() throws Throwable {
    ...
}

Is it common practice to do

9条回答
  •  醉酒成梦
    2020-12-30 21:25

    In some rare cases it is acceptable to throw Throwables. For example, @Around advices in Spring AOP are usually declared to throw a Throwable.

    The following example is copied verbatim from Spring AOP docs:

      import org.aspectj.lang.annotation.Aspect;
      import org.aspectj.lang.annotation.Around;
      import org.aspectj.lang.ProceedingJoinPoint;
    
      @Aspect
      public class AroundExample {
    
          @Around("com.xyz.myapp.SystemArchitecture.businessService()")
          public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
              // start stopwatch
              Object retVal = pjp.proceed();
              // stop stopwatch
              return retVal;
          }
    
      }
    

    Why is doBasicProfiling declared to throw a Throwable? Because the original method (i.e. the execution join point), might throw an Error, RuntimeException, or a checked exception. So it only makes sense to declare doBasicProfiling to throw a Throwable.

提交回复
热议问题