Is there a better way to throw this exception?

John Rose john.r.rose at oracle.com
Fri Jun 7 22:44:11 UTC 2013


Puzzles!
Probably you can use the new syntax "catch (Ex1|Ex2 ex)" to bind the first exception to a union type.
You'll have to split the loop, but you could use a common iterator.

for (Iterator it = all changes; it.hasNext(); ) {
  try {
    it.next(); once(); return;
  } catch (One|Two ex) {
    while (it.hasNext()) {
      try { it.next(); once(); return; }
      catch (One|Two ex) { /*ignore all but 1st*/ }
    }
    throw ex; /*throw 1st*/
  }
}

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?
> 
> Thanks
> Max




More information about the core-libs-dev mailing list