Is there a better way to throw this exception?

David Holmes david.holmes at oracle.com
Fri Jun 7 07:53:06 UTC 2013


Peter,

On 7/06/2013 12:57 AM, Peter Levart wrote:
> On 06/06/2013 11:42 AM, Weijun Wang 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?
>
> Hi Max,
>
> If you don't mind re-throwing the last exception thrown instead of the
> first and you can transform your for loop into a while loop, for example:
>
>      void multiple() throws One, Two {
>          int tries = 10;
>          int i = 0;
>          while (true) {
>              try {
>                  once();
>                  return;
>              } catch (Exception e) {
>                  if (++i >= tries) {
>                      throw e;
>                  }
>              }
>          }
>      }
>
>
> ...otherwise you can re-throw the first exception if you can extract the
> first loop iteration out of the loop:
>
>
>      void multiple() throws One, Two {
>          try {
>              once(); // first chance
>              return;
>          } catch (Exception e) {
>              for (rest of chances) {
>                  try {
>                      once();
>                      return;
>                  }
>                  catch (Exception ignore) {}
>              }
>              throw e;
>          }
>      }

But the first call need not throw.

David
-----


>
> Regards, Peter
>
>>
>> Thanks
>> Max
>



More information about the core-libs-dev mailing list