Is there a better way to throw this exception?

Steven Schlansker stevenschlansker at gmail.com
Thu Jun 6 15:35:56 UTC 2013


On Jun 6, 2013, at 2:42 AM, Weijun Wang <weijun.wang at oracle.com> wrote:

> Hi All
> 
> I have a method that could throw two kinds of checked exceptions and possibly other unchecked ones:
> 
>   void once() throws One, Two
> 
> Now I have a wrapper method that calls once() for multiple times, and want to throw the first exception if *all* fails. Now it looks like
> 
>   void multiple() throws One, Two {
>      Exception saved = null;
>      for (all chances) {
>         try {
>            once();
>            return;
>         } catch (Exception e) {
>            if (saved != null) saved = e;
>         }
>      }
>      if (saved instanceof One) {
>         throw (One)saved;
>      } else if (saved instanceof One) {
>         throw (Two)saved;
>      } else if (saved instanceof RuntimeException) {
>         throw (RuntimeException)saved;
>      } else {
>         // Not likely, but I've already wrote so many lines.
>         throw new RuntimeException(saved);
>      }
>   }
> 
> Is there any way I can make it shorter?

If you use / are willing to use Guava, you can replace all of the exception if clauses with:

void multiple() throws One, Two {
    for (…) {
        …
    }
    Throwables.propagateIfPossible(saved, One.class, Two.class);
    throw Throwables.propagate(saved);
}

http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Throwables.html#propagateIfPossible(java.lang.Throwable,%20java.lang.Class,%20java.lang.Class)




More information about the core-libs-dev mailing list