Rethrow在java中捕获异常

时间:2013-04-21 19:22:45

标签: java exception throw throws rethrow

我有以下下载功能。我在路上捕获了一些可能的异常,并将它们存储在Exception类型变量中,并且在finally块中清理之后,我想重新抛出原始异常(如果有一个被捕获)或者抛出我自己的自定义DownloadFailedException 。问题是Eclipse给了我“Unhandled exception type Exception”错误,因为我的函数没有声明抛出Exception。有一种“好”的方法吗?

public static boolean downloadFile(String urlString, String dstPath) throws DownloadFailedException, IOException {
    if (!Settings.isNetworkAvailable()) {
        throw new NoNetworkException("Network error: no internet connection. Failed downloading " + urlString);
    }
    InputStream input = null;
    BufferedOutputStream output = null;
    int fileLength = -1;
    long total = 0;
    int statusCode = -1;
    HttpGet get = new HttpGet(urlString);
    get.setHeader("User-Agent", Settings.getUserAgent());
    get.setHeader("X-My-Id", Settings.getDeviceId());
    HttpClient client = new DefaultHttpClient();
    HttpResponse response = null;
    try {
        response = client.execute(get);
        statusCode = response.getStatusLine().getStatusCode();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (200 != statusCode) {
            throw new DownloadFailedException("http error: " + statusCode +". Failed downloading " + urlString, statusCode);
        }
    }
    if (null != response) {
        HttpEntity entity = response.getEntity();
        File tmpFile = null;
        Exception exception = null;
        try {
            InputStream is = entity.getContent();
            byte b[] = new byte[1];
            is.read(b, 0, 0);
            fileLength = (int)entity.getContentLength();
            input = new BufferedInputStream(is, 8192);
            tmpFile = new File(dstPath + ".tmp");
            tmpFile.createNewFile();
            output = new BufferedOutputStream(new FileOutputStream(tmpFile), 8192);

            byte data[] = new byte[8192];
            int count;
            while ((count = input.read(data)) != -1) {
                total += count;
                output.write(data, 0, count);
            }
        } catch (IllegalStateException e) {
            exception = e;
            e.printStackTrace();
        } catch (IOException e) {
            exception = e;
            e.printStackTrace();
        } finally {
            try {
                if (null != output) {
                    output.flush();
                    output.close();
                }
                if (null != input)
                    input.close();
            } catch (IOException e) {
                if (null == exception)
                    exception = e;
            }
            if (-1 < fileLength && total != fileLength) {
                if (null != tmpFile) {
                    tmpFile.delete();
                }
                if (null != exception) {
// HERE I WOULD LIKE TO RE-THROW THE ORIGINAl EXCEPTION
                    throw exception; // Unhandled exception type Exception
                    //also tried: exception.getClass().cast(exception);
                } else
                    throw new DownloadFailedException(urlString + ": only " + total + " bytes read out of " + fileLength);
            }
            File dstFile = new File(dstPath);
            tmpFile.renameTo(dstFile);
        }
        return true;
    }
    return false;
}

SOLUTION:

if (null != exception) {
    if (exception instanceof IllegalStateException)
        throw (IllegalStateException) exception;
    else if (exception instanceof IOException)
        throw (IOException) exception;
    else
        throw new RuntimeException(message, exception);
}
//throw new IOException("Only " + total + "bytes read from " + fileLength);
throw new DownloadFailedException(message);

1 个答案:

答案 0 :(得分:2)

你在哪里:

// HERE I WOULD LIKE TO RE-THROW THE ORIGINAl EXCEPTION
throw exception; // Unhandled exception type Exception
// also tried: exception.getClass().cast(exception);

我会用这个:

if(exception instanceof IOException)
    throw (IOException) exception;
else
    throw new DownloadException(exception);

根据您描述的情况和方法末尾的throws子句,该代码执行您想要执行的操作。在英语中,这是代码的作用:

  • 如果您抓到Exception并且它是IOException,那么您想要抛出IOException
  • 如果你抓到Exception并且它不是IOException,你想要抛出DownloadException(你自己的创作)。我们将所有非IOException包装在DownloadException中,以便您的实现与您方法中的throws子句保持一致。
  • 如果你没有抓到Exception,那么你希望生活能够正常继续

请注意,在编译之前,您可能需要向类public DownloadException(Throwable e){super(e);}添加类似DownloadException的构造函数(如果具有该签名的构造函数尚未存在)。