public class TryWithResource {
public static void main(String[] args) throws Exception {
try {
tryWithResourceException();
} catch (Exception e) {
System.out.println(e.getMessage());
}
try {
normalTryException();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
private static void normalTryException() throws Exception {
MyResource mr = null;
try {
mr = new MyResource();
System.out.println("MyResource created in try block");
if (true)
throw new Exception("Exception in try");
} finally {
if (mr != null)
mr.close();
}
}
private static void tryWithResourceException() throws Exception {
try (MyResource mr = new MyResource()) {
System.out.println("MyResource created in try-with-resources");
if (true)
throw new Exception("Exception in try");
}
}
static class MyResource implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println("Closing MyResource");
throw new Exception("Exception in Closing");
}
}
}
output;
MyResource created in try-with-resources
Closing MyResource
Exception in try
MyResource created in try block
Closing MyResource
Exception in Closing
how its work:
tryWithResourceException called
print: MyResource created in try-with-resources
before throw exception autoclose will call then print Closing MyResource and throw Exception in closing but its override by Exception in try
normalTryException called
print: MyResource created in try block and throw exception Exception in try but its overrride by finally
public static void main(String[] args) throws Exception {
try {
tryWithResourceException();
} catch (Exception e) {
System.out.println(e.getMessage());
}
try {
normalTryException();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
private static void normalTryException() throws Exception {
MyResource mr = null;
try {
mr = new MyResource();
System.out.println("MyResource created in try block");
if (true)
throw new Exception("Exception in try");
} finally {
if (mr != null)
mr.close();
}
}
private static void tryWithResourceException() throws Exception {
try (MyResource mr = new MyResource()) {
System.out.println("MyResource created in try-with-resources");
if (true)
throw new Exception("Exception in try");
}
}
static class MyResource implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println("Closing MyResource");
throw new Exception("Exception in Closing");
}
}
}
output;
MyResource created in try-with-resources
Closing MyResource
Exception in try
MyResource created in try block
Closing MyResource
Exception in Closing
how its work:
tryWithResourceException called
print: MyResource created in try-with-resources
before throw exception autoclose will call then print Closing MyResource and throw Exception in closing but its override by Exception in try
normalTryException called
print: MyResource created in try block and throw exception Exception in try but its overrride by finally
No comments:
Post a Comment