开发者

How to implement `finally` for error case in Java

开发者 https://www.devze.com 2023-01-29 14:25 出处:网络
I need some code to be triggered if any error occurs.Basically I need a finally block which executes only in case of an exception.I would implement it this way:

I need some code to be triggered if any error occurs. Basically I need a finally block which executes only in case of an exception. I would implement it this way:

HttpURLConnection post(URL url, byte[] body) throws IOException {
    HttpURLConnection connection = url.openConnection();
    try {
        OutputStream out = connection.getOutputStream();
        try {
            out.write(body);
        } finally {
            out.close();
        }
        return connection;
    } catch (Throwable t) {
        connection.disconnect();
        throw t;
    }
}

Looks fine—except it won't compile: my f开发者_如何转开发unction cannot throw Throwable.

I could re-write:

    } catch (RuntimeException e) {
        connection.disconnect();
        throw e;
    } catch (IOException e) {
        connection.disconnect();
        throw e;
    }

But even then I'm a) missing all Errors and b) have to fix this code any time I change my implementation to throw different types of exceptions.

Is it possible to handle this generically?


You could use a finally block, and add a flag to indicate success.

bool success = false;
try {
    //your code
    success = true;
    return retVal;
} finally {
    if (!success) {
        //clean up
    }
}


Throwable has two subclasses, Error and Exception. Javadocs for Error say:

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it.

So unless this is a truly unusual situtation, you can just focus on Exception:

catch (IOException e) {
    connection.disconnect();
    throw e;
}
catch (RuntimeException e) {
    connection.disconnect();
    throw e;
}
catch (Exception e) {
    connection.disconnect();
    throw new IOException(e);
}


Unless I am mistaken an Exception would not need a finally block to stop execution and do something you need, like clean up or error mitigation.

try {
  // Do some work! 
  // Fail
} catch (IOException e) {
  // Clean up, alert user, expected error
} catch (Exception e) {
  // Not so much expected, but lets try to handle this
}

The errors should come from your implemented classes and methods which are basically your ideas. Think about the flow of execution and the propagation of errors. If your method above doesn't catch a particular exception then whatever called it will see the exception.

Throwable is just a top level class with subclasses. Exception being generally a catch all. And remember you can also implement your own exceptions to handle task.

0

精彩评论

暂无评论...
验证码 换一张
取 消