Is there something like Python with context manager in Java?
For example say I want to do something like the following:
getItem(itemID){
Connection c = C.getConnection();
c.open();
try{
Item i = c.query(itemID);
}catch(ALLBunchOfErrors){
c.close();
}
c.close();
return c;
}
where in python I just have:
with( C.getConnection().open() as c):
Item i = c.query(itemID);
return i;
Java 7 has introduced a new feature to address this issue: "try with resources"
http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Close resource quietly using try-with-resources
The syntax is to place the resource in parentheses after the try keyword:
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
Prior to Java 7, you can use a finally block.
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
Not at the moment; Java still hasn't added syntactic sugar for this pattern. Still, it won't get as clean as with(Python) or using(C#), but you can at least clean that up a little bit by just having one call to c.close() inside a finally block, instead of twice as you've done:
try {
// use c
} finally {
c.close()
}
This also brings it in line with how both with and using are actually implemented, which is a try..finally block (not a try..catch).
As tzaman said, the secret is using finally; generally:
Resource r = allocateResource();
try {
// use resource
}
finally {
r.dispose();
}
Things to note here:
try and finally each create a variable scope. So allocating your resource within the try clause won't work, as it won't be visible in the finally clause- you've got to declare the resource's variable before the try statement.
If you have several resources to allocate, the general pattern applies cleanly, but this is often not evident to beginners:
Resource1 r1 = allocateResource1();
try {
// code using r1, but which does not need r2
Resource r2 = allocateResource2();
try {
// code using r1 and r2
}
finally {
r2.dispose();
}
}
finally {
r1.dispose();
}
, and so on and so forth if you have more resources to allocate. If you have a couple of them, you will surely be tempted to try and avoid deep nesting of try... finally statements. Don't. You can get resource deallocation and exception handling right without nesting so many try... finally statements, but getting it right without nesting try... finally is even uglier than deep nesting.
If you frequently need to use a set of resources, you can implement a functor-based method to avoid the repetition, something like:
interface WithResources {
public void doStuff(Resource1 r1, Resource2 r2);
}
public static void doWithResources(WithResources withResources) {
Resource r1 = allocateResource1();
try {
Resource r2 = allocateResource2();
try {
withResources.doStuff(r1, r2);
}
finally {
r2.dispose();
}
}
finally {
r1.dispose();
}
}
Which then you can use like this:
doWithResources(new WithResources() {
public void doStuff(Resource1 r1, Resource2 r2) {
// code goes here
}
});
doWithResources will automatically handle allocation and deallocation correctly, and your code will have less repetition (which is a good thing). However:
Java's syntax for anonymous classes is excessively verbose
Checked exceptions within doStuff complicate things too much
, two points which I hope will be solved in Java 7.
You can find this kind of code throughout Spring, for instance:
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/classic-spring.html#orm-hibernate-template ; doInHibernate thingy.
There's an alternative using a generic wrapper like this:
final _<Item> item = new _<Item>();
final _<Connection> c = new _<Connection>();
with( factory, c, new Runnable() {
public void run(){
item._ = c._.query( itemId );
}
});
return item._;
NOTE: The Java way is the one you've just described. This other is just for "fun" and experimentation:
The _ is a generic wrapper and the with function is an utility class defined somewhere else as:
class WithUtil {
public static void with( ConnectionFactory factory,
_<Connection> c, Runnable block ) {
try {
c._ = factory.getConnection();
c._.open();
block.run();
} catch( Exception ioe ){
}finally{
if( c._ != null ) try {
c._.close();
} catch( IOException ioe ){}
}
}
}
In strict theory, you could re-use it to perform other stuff, like deleting an item:
public void deleteItem( final int itemId ) {
final _<Connection> c = new _<Connection>();
with( factory, c, new Runnable() {
public void run(){
Item item = c._.query( itemId );
if( ! item.hasChildren() ) {
c._.delete( item );
}
}
});
}
or update it
public void update( final int itemId, String newName ) {
final _<Connection> c = new _<Connection>();
with( factory, c, new Runnable() {
public void run(){
Item item = c._.query( itemId );
item.setName( newName );
c._.update( item );
}
});
}
Without having to integrate the try/catch again.
Here's a full working demo that proofs the concept ( and doesn't do anything else )
try-with-resources was introduced in Java 7. Prior to that you had to use try-finally blocks. See documentation here: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Related
For user code, there are a couple of options for correctly closing multiple resources:
1. try-with-resources
try (
A a = new A();
B b = new B();
C c = new C()
) {
// ...
}
Apart from being nice and short, it is also correct.
It will correctly close whichever of a, b and c needs closing.
Additionally, it will also "suppress" exceptions which occur during close if exception is thrown from the body (this is an improvement over try/finally as can be read here https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)
2. Guava Closer
For pre-JDK7 there is Guava's Closer which is used like:
Closer closer = Closer.create();
try {
A a = closer.register(new A());
B b = closer.register(new B());
C c = closer.register(new C());
// ...
} catch (Throwable e) { // must catch Throwable
throw closer.rethrow(e);
} finally {
closer.close();
}
While slightly longer, it also works pretty good (check here https://github.com/google/guava/wiki/ClosingResourcesExplained#closer for more info)
What about objects holding multiple resources?
Say I have:
public class P implements AutoCloseable {
private A a;
private B b;
private C c;
public P() {
a = new A();
b = new B();
c = new C();
}
public close() {
c.close();
b.close();
a.close();
}
}
There are multiple problems with this code:
If exception is thrown from the constructor, nothing will be closed (the caller does not have the instance on which to call close)
If exception is thrown from close, some resources will not be closed
Neither 1 nor 2 suffered from these issues. However:
try-with-resources obviously cannot be used, as lifetime of P is controlled by the caller
Guava Closer seems cannot be used either. While it is more flexible, it does not support close-and-rethrow, which is necessary from the constructor
What is the correct pattern here for N resources without too much boilerplate? The solution should also have the suppression property of 1 and 2
If exception is thrown from the constructor, nothing will be closed (the caller does not have the instance on which to call close)
You can catch any Exception that is thrown during the initialization of the individual resources and close all the resources initialized so far and throw back one Exception denoting initialization failed.
If exception is thrown from close, some resources will not be closed
Same as above, but this time it denoting closing of some resources failed.
This solution makes the below assumption:
If you take your original code snippet having a try with resources with three resources A, B and C,
if initialization of any of those failed or the try block throws an Exception and
the close method of one or more of them throws an Exception,
then only the Exception thrown from 1 is thrown back and the exception(s) from 2 is suppressed and can be obtained by calling the Throwable's getSuppressed.
However, when you are abstracting the individual resources with a wrapper class, I don't believe we must have the same behaviour i.e, adding close method failures (exceptions) to suppressed exceptions. In other words, all those resources must be abstracted by the wrapper and must not throw any exception specific to one resource.
The entire initialization code is wrapped in a single try..catch block. If any of the resource initialization fails, it closes all the opened resources and throws back one Exception to denote that the initialization of the wrapper resource failed. If any of the close fails here, it is silenced (and cannot be obtained via getSuppressed by the caller).
When closing the wrapper resource, each of the individual resources are closed and if any of them fails, again one Exception denoting the closing of the wrapper resource failed is thrown back.
Let Resources be the class that holds multiple closeable resources.
public class Resources implements AutoCloseable {
private MyCloseable1 myCloseable1;
private MyCloseable2 myCloseable2;
public Resources() {
try {
myCloseable1 = new MyCloseable1();
myCloseable2 = new MyCloseable2();
} catch (Exception e) {
close(false, myCloseable1, myCloseable2);
throw new RuntimeException("Initialization failed");
}
}
#Override
public void close() throws Exception {
close(true, myCloseable1, myCloseable2);
}
private void close(boolean throwExceptionIfFailed, AutoCloseable... autoCloseables) {
boolean closeFailed = false;
for (AutoCloseable autoCloseable : autoCloseables) {
try {
if (autoCloseable != null) {
autoCloseable.close();
}
} catch (Exception e) {
//Add logs here.
closeFailed = true;
}
}
/*
Using Java 8 streams and reduce.
closeFailed = Arrays.stream(autoCloseables)
.filter(Objects::nonNull)
.reduce(false, (isFailed, autoCloseable) -> {
try {
autoCloseable.close();
} catch (Exception e) {
return true;
}
return isFailed;
}, (isFailed1, isFailed2) -> isFailed1 || isFailed2);
*/
if (closeFailed && throwExceptionIfFailed) {
throw new RuntimeException("Closing of Resources failed");
}
}
}
Usage:
try (Resources resources = new Resources()) {
....
} catch (Exception e) {
....
}
I would suggest doing this:
public close() throws ... {
try (A aa = a;
B bb = b;
C cc = c) {
// empty
}
}
We are simply using the standard try-with-resource mechanism to close the resources that were opened previously. This will deal with the cases where a, b or c are null, and where the close() calls throw an exception.
For the constructor:
public P() throws ... {
try {
a = new A();
b = new B();
c = new C();
} finally {
if (!(a != null && b != null && c != null)) {
close();
}
}
It is more complicated if you want to suppress exceptions thrown by close() in the constructor.
You can hide opening and closing of resources from your resources wrapper class' users with execute around method pattern. This way you will ensure resources will always be closed. You should add separate operation methods for different use-cases. This will only be usefull if this is a common resource and used by many part of the application.
Here is a sample
public class ResourceWrapper {
private A a;
private B b;
private C c;
private ResourceWrapper() {
// add try catch if you have to, after cleanup then throw exception if ithappens
a = new A();
b = new B();
c = new C();
}
/**
* add required operation methods
*/
public ResourceWrapper op1() {
// do some operations
return this;
}
public ResourceWrapper op2() {
// if additional add or different
return this;
}
// close everything here
private void close() {
// check null if you have to
// add try catch if you have to
c.close();
b.close();
a.close();
}
public static void use(Consumer<ResourceWrapper> consumer) {
ResourceWrapper resource = null;
try {
resource = new ResourceWrapper();
consumer.accept(resource);
}
finally {
if(resource!=null) {
resource.close();
}
}
}
}
public class SampleResourceUser {
/*
* This represents the user of the Resource,
* User only cares about which operations that needs to be done on the resource.
* Opening and closing the resource wrapped around the operation methods by the owner of the Resource.
*
*/
public static void main(String[] args) {
ResourceWrapper.use(resource->resource.op1().op2());
}
}
Is it possible to make an exception that is optional to be caught?
In other words, an exception that can either:
be caught in a try-catch block
or skipped if no try-catch block exists for it
To visualize, I have a ReportedException, which is just a plain subclass of RuntimeException, and want to be able to catch it when it's needed:
try
{
hideWindow();
}
catch (ReportedException ex)
{
// Window could not be hidden.
// Exception has already been caught and logged by parseInput(),
// and now we're going to do something more.
printAdditionalErrorMessage();
}
Note: I edited the above example to better fit my question.
or skip catching if the result is irrelevant:
hideWindow(); // We don't care if there was an error or not.
openAnotherWindow();
I know I can leave the catch block empty and have the same thing as above, but I use ReportedException very often and it would make my code highly unreadable.
If it's impossible (I suspect it is), what alternative/walkaround would you recommend?
P.S. The method names used in the examples are just foo's and bar's.
EDIT: I know I don't need to catch RuntimeExceptions. What I want is to ignore them if they occur.
Exceptions should be used for exceptional situations.
From your example, if the window not being hidden is a typical event, it shouldn't throw an exception. If that is your function, then use a return value to indicate whether it was successful instead of throwing an exception. Then you can safely ignore the return value when you don't care if it succeeded or not.
If you do not have control over that method, then you can wrap it in another method that catches the exception and turns it into a return value. E.g.
private boolean tryHideWindow() {
try {
hideWindow();
}
catch (ReportedException ex) {
return false;
}
return true;
}
If you need some parameters of the exception to determine what to do, then you could return the exception instead.
private static class MyReturnType {
private final Throwable thrown;
private final OrigRtnType returnVal;
public MyReturnType(Throwable thrown) {
this.thrown = thrown;
this.returnVal = null;
}
public MyReturnType(OrigRtnType returnVal) {
this.thrown = null;
this.returnVal = returnVal
}
public boolean wasExceptionThrown() {
return thrown != null;
}
}
private MyReturnType tryHideWindow() {
try {
OrigRtnType returnVal = hideWindow();
}
catch (ReportedException ex) {
return new MyReturnType(ex);
}
return new MyReturnType(returnVal);
}
This is an answer to your question, but it is not necessarily a good idea. As others will doubless comment, using exceptions for program flow is less than ideal.
I'm a little fuzzy on how to use ThreadLocal (and there are apt to be some other tupos), but something like this:
public class IgnorableException {
static class DontIgnoreCount {
int count;
}
// Thread local variable containing each thread's ID
private static final ThreadLocal<DontIgnoreCount> dontIgnoreCount =
new ThreadLocal<DontIgnoreCount>();
static void incrementDontIgnore() {
DontIgnoreCount counter = dontIgnoreCount.get();
if (counter == null) {
counter = new DontIgnoreCount();
dontIgnoreCount.set(counter);
}
counter.count++;
}
static void decrementDontIgnore() {
DontIgnoreCount counter = dontIgnoreCount.get();
// Must not be null here
counter.count--;
static bool shouldSignal() {
DontIgnoreCount counter = dontIgnoreCount.get();
return counter.count > 0;
}
}
To use, invoke DontIgnoreCount.incrementIgnoreCount() early in try range, and DontIgnoreCount.decrementIgnoreCount() late in finally range.
When signalling an exception that follows this protocol, only signal it if shouldSignal returns true.
void iWannaCatchException() {
try {
IgnornableException.incrementDontIgnore();
int x = someOptionallySignallingMethod();
}
catch (...) {
...
}
finally {
IgnorableException.decrementDontIgnore();
}
}
void iDontWannaCatchException() {
int x = someOptionallySignallingMethod();
}
int someOptionallySignallingMethod() {
if (somethingBad) {
if (IgnorableException.shouldSignal()) {
throw new BadException();
}
}
return 42;
}
Note that not shown above are any throws clauses you'd have to add to keep the compiler happy. This mechanism would not remove the need for those.
You could also inplement a delegate/observer scheme, replacing the simple counter with a stack of observer objects, and pass a message to the observer vs throwing the exception. But this, by itself (without coupled exceptions/try ranges) would not allow blowing away the stack to the appropriate recovery point.
It sounds like you want to use exceptions for flow control, rather than for reporting truly exceptional cases.
Using exceptions for flow control is typically frowned upon. The common approach is to return a success/failure indication as the return value of the function.
You can use something like this:
try{
hideWindow();
}catch (ReportedException ex){
// ingore
}catch (NullPointerException ex){
killWindow();
}finally {
//to do something more.
}
I want to continue with the next line from which error generated,
try{
statement A;
statement B;
statement C;
}
catch(NullPointerException NPE){.....}
Now assume that my statement A throws exception so I want to skip that and continue with B. Don't give my suggestion to put in catch/finally block or any other solution. I just want to know is this possible to skip and continue with next statement?
Yes, it is possible without the finally block.
try{
statement A;
}
catch(NullPointerException NPE){.....}
try{
statement B;
}
catch(NullPointerException NPE){.....}
try{
statement C;
}
catch(NullPointerException NPE){.....}
On the side note, I don't really think this is nice. If you managed to come to the point where you need this kind of flow control, you need to take a step back and rethink your code design.
It is not possible to execute statement B if A throws exception. One way is seperately try/catch block and other way is put other lines into finally block.
If your statements are similar and can be paramerized, use a loop:
for (int i = 0; i < statementCount; i++) {
try {
/** do what you need */
} catch(Exception e) {
}
}
or put it in separate method if it needs more parameters:
public static void main(String[] args) {
for (int i = 0; i < statementCount; i++) {
}
execute(params);
}
public void execute(Object... objects) {
try {
doSomthing(objects[0], objects[1]);
} catch(Exception e) {
}
}
If statements are abolutely different, Java 8 provides interesting solutions: method references and lambdas. So you can play arround with somthing like this:
public static void main(String[] args) {
execute(someObject, YourClass::method);
}
public void execute(Object param, Function<Object, Void> function) {
try {
function.apply(param);
} catch(Exception e) {
}
}
Like darijan already mentioned you could put every single statement into an own try-catch. Or if you know what may cause the exception you can simply check it befor you execute your statements
try{
if(parameterForStatementA != null) {
statementA;
}
if(parameterForStatementB != null) {
statementB;
}
if(parameterForStatementC != null) {
statementC;
}
} catch(Exception e) {
// something unexpected happened
}
Verifying parameters is usually more efficient than catching thrown exceptions
In .net the AggregateException class allows you to throw an exception containing multiple exceptions.
For example, you would want to throw an AggregateException if you ran multiple tasks in parallel and some of them failed with exceptions.
Does java have an equivalent class?
The specific case I want to use it in:
public static void runMultipleThenJoin(Runnable... jobs) {
final List<Exception> errors = new Vector<Exception>();
try {
//create exception-handling thread jobs for each job
List<Thread> threads = new ArrayList<Thread>();
for (final Runnable job : jobs)
threads.add(new Thread(new Runnable() {public void run() {
try {
job.run();
} catch (Exception ex) {
errors.add(ex);
}
}}));
//start all
for (Thread t : threads)
t.start();
//join all
for (Thread t : threads)
t.join();
} catch (InterruptedException ex) {
//no way to recover from this situation
throw new RuntimeException(ex);
}
if (errors.size() > 0)
throw new AggregateException(errors);
}
Java 7's Throwable.addSuppressed(Throwable) will do something similar, although it was built for a slightly different purpose (try-with-resource)
I'm not aware of any built-in or library classes, as I've never even though of wanting to do this before (typically you would just chain the exceptions), but it wouldn't be that hard to write yourself.
You'd probably want to pick one of the Exceptions to be "primary" so it can be used to fill in stacktraces, etc.
public class AggregateException extends Exception {
private final Exception[] secondaryExceptions;
public AggregateException(String message, Exception primary, Exception... others) {
super(message, primary);
this.secondaryExceptions = others == null ? new Exception[0] : others;
}
public Throwable[] getAllExceptions() {
int start = 0;
int size = secondaryExceptions.length;
final Throwable primary = getCause();
if (primary != null) {
start = 1;
size++;
}
Throwable[] all = new Exception[size];
if (primary != null) {
all[0] = primary;
}
Arrays.fill(all, start, all.length, secondaryExceptions);
return all;
}
}
You can represent multiple taska as
List<Callable<T>> tasks
Then if you want the computer to actually do them in parallel use
ExecutorService executorService = .. initialize executor Service
List<Future<T>> results = executorService.invokeAll ( ) ;
Now you can iterate through the results.
try
{
T val = result . get ( ) ;
}
catch ( InterruptedException cause )
{
// this is not the exception you are looking for
}
catch ( ExecutionExeception cause )
{
Throwable realCause = cause . getCause ( ) // this is the exception you are looking for
}
So realCause (if it exists) is whatever exception what thrown in its associated task.
I don't really see why you should use exceptions in the first place to mark tasks as incomplete/failed but in any case, it shouldn't be hard to create one yourself. Got any code to share so that we could help you with a more specific answer?
I've seen reference in some C# posted questions to a "using" clause.
Does java have the equivalent?
Yes. Java 1.7 introduced the try-with-resources construct allowing you to write:
try(InputStream is1 = new FileInputStream("/tmp/foo");
InputStream is2 = new FileInputStream("/tmp/bar")) {
/* do stuff with is1 and is2 */
}
... just like a using statement.
Unfortunately, before Java 1.7, Java programmers were forced to use try{ ... } finally { ... }. In Java 1.6:
InputStream is1 = new FileInputStream("/tmp/foo");
try{
InputStream is2 = new FileInputStream("/tmp/bar");
try{
/* do stuff with is1 and is 2 */
} finally {
is2.close();
}
} finally {
is1.close();
}
Yes, since Java 7 you can rewrite:
InputStream is1 = new FileInputStream("/tmp/foo");
try{
InputStream is2 = new FileInputStream("/tmp/bar");
try{
/* do stuff with is1 and is2 */
} finally {
is2.close();
}
} finally {
is1.close();
}
As
try(InputStream is1 = new FileInputStream("/tmp/foo");
InputStream is2 = new FileInputStream("/tmp/bar")) {
/* do stuff with is1 and is2 */
}
The objects passed as parameters to the try statement should implement java.lang.AutoCloseable.Have a look at the official docs.
For older versions of Java checkout this answer and this answer.
The nearest equivalent within the language is to use try-finally.
using (InputStream in as FileInputStream("myfile")) {
... use in ...
}
becomes
final InputStream in = FileInputStream("myfile");
try {
... use in ...
} finally {
in.close();
}
Note the general form is always:
acquire;
try {
use;
} finally {
release;
}
If acquisition is within the try block, you will release in the case that the acquisition fails. In some cases you might be able to hack around with unnecessary code (typically testing for null in the above example), but in the case of, say, ReentrantLock bad things will happen.
If you're doing the same thing often, you can use the "execute around" idiom. Unfortunately Java's syntax is verbose, so there is a lot of bolier plate.
fileInput("myfile", new FileInput<Void>() {
public Void read(InputStream in) throws IOException {
... use in ...
return null;
}
});
where
public static <T> T fileInput(FileInput<T> handler) throws IOException {
final InputStream in = FileInputStream("myfile");
try {
handler.read(in);
} finally {
in.close();
}
}
More complicated example my, for instance, wrap exceptions.
It was a long time coming but with Java 7 the try-with-resources statement was added, along with the AutoCloseable interface.
Not that I'm aware of. You can somewhat simulate with a try...finally block, but it's still not quite the same.
The closest you can get in Java is try/finally. Also, Java does not provide an implicit Disposable type.
C#: scoping the variable outside a using block
public class X : System.IDisposable {
public void Dispose() {
System.Console.WriteLine("dispose");
}
private static void Demo() {
X x = new X();
using(x) {
int i = 1;
i = i/0;
}
}
public static void Main(System.String[] args) {
try {
Demo();
} catch (System.DivideByZeroException) {}
}
}
Java: scoping the variable outside a block
public class X {
public void dispose() {
System.out.println("dispose");
}
private static void demo() {
X x = new X();
try {
int i = 1 / 0;
} finally {
x.dispose();
}
}
public static void main(String[] args) {
try {
demo();
} catch(ArithmeticException e) {}
}
}
C#: scoping the variable inside a block
public class X : System.IDisposable {
public void Dispose() {
System.Console.WriteLine("dispose");
}
private static void Demo() {
using(X x = new X()) {
int i = 1;
i = i/0;
}
}
public static void Main(System.String[] args) {
try {
Demo();
} catch (System.DivideByZeroException) {}
}
}
Java: scoping the variable inside a block
public class X {
public void dispose() {
System.out.println("dispose");
}
private static void demo() {
{
X x = new X();
try {
int i = 1 / 0;
} finally {
x.dispose();
}
}
}
public static void main(String[] args) {
try {
demo();
} catch(ArithmeticException e) {}
}
}
I think you can achieve something similar to the "using" block, implementing an anonymous inner class. Like Spring does with the "Dao Templates".
Well, using was syntactic sugar anyway so Java fellows, don't sweat it.
If we get BGGA closures in Java, this would also open up for similar structures in Java. Gafter has used this example in his slides, for example:
withLock(lock) { //closure }
The actual idiom used by most programmers for the first example is this:
InputStream is1 = null;
InputStream is2 = null;
try{
is1 = new FileInputStream("/tmp/bar");
is2 = new FileInputStream("/tmp/foo");
/* do stuff with is1 and is 2 */
} finally {
if (is1 != null) {
is1.close();
}
if (is2 != null) {
is2.close();
}
}
There is less indenting using this idiom, which becomes even more important when you have more then 2 resources to cleanup.
Also, you can add a catch clause to the structure that will deal with the new FileStream()'s throwing an exception if you need it to. In the first example you would have to have another enclosing try/catch block if you wanted to do this.
No there isn't.
You can
public void func(){
{
ArrayList l = new ArrayList();
}
System.out.println("Hello");
}
This gives you the limited scope of the using clause, but there isn't any IDisposable interface to call finalization code. You can use try{}catch(){}Finally{}, but it doesn't have the sugar of using. Incidentally using finalizers in Java is generally a bad idea.
No, there is no using in Java, the most similar functionality is the "import" keyword.