Where you have:
// HERE I WOULD LIKE TO RE-THROW THE ORIGINAl EXCEPTION
throw exception; // Unhandled exception type Exception
// also tried: exception.getClass().cast(exception);
I would use this:
if(exception instanceof IOException)
throw (IOException) exception;
else
throw new DownloadException(exception);
Based on the situation you described and the throws
clause at the end of your method, that code does what you want to do. In English, here's what that code does:
- If you catch an
Exception
and it's anIOException
, then you want to throw anIOException
- If you catch an
Exception
and it's not anIOException
, you want to throw aDownloadException
(of your own creation). We wrap any non-IOException
in aDownloadException
so that your implementation is consistent with thethrows
clause on your method. - If you do not catch an
Exception
, then you want life to continue as normal
Note that you may need to add a constructor like public DownloadException(Throwable e){super(e);}
to your class DownloadException
(if a constructor with that signature doesn't already exist) before this will compile.