Is there any helper method in the JDK or common libraries that does this:
if (resource instanceof AutoCloseable) {
((AutoCloseable) resource).close();
}
Just a one-liner to call an object's close() if applicable.
I know about try-with-resources, that's not applicable to this situation. And I know that not all classes that have a close() method implement AutoCloseable. But, I seem to write the above over and over..
There's something Apache Commons offers:
http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/IOUtils.html#closeQuietly(java.io.Closeable)
Here is apache commons closeQuietly adapted for AutoCloseable:
static void closeQuietly(AutoCloseable closeable) {
try {
if (closeable != null) {
closeable.close();
}
}
catch (Exception swallowed) {
}
}
since google sent me here for that case :)
Edit:
Check this:
class CloserHelper
{
public static void close(Object object)
{
if (object instanceof AutoCloseable)
{
try
{
((AutoCloseable) object).close();
}
catch (Exception ignored) { }
}
}
}
I can think to something like this
class CloserHelper
{
public static void close(AutoCloseable obj) throws Exception
{
obj.close();
}
}
Then
CloserHelper.close(resource);
If the object is not a AutoCloseable you cannot just call it
If you want to ignore exceptions
class CloserHelper
{
public static void close(AutoCloseable obj)
{
try
{
obj.close();
}
catch (Exception e) { }
}
}
Related
I have a class that has many methods. All the methods throw one exception when data is not ready. In that case, I want to retry the method after a certain interval. So in catch, I need to add retry logic. The same logic i need to add for all methods.
Is there some way/pattern to execute same logic for all catch clause without copy paste
One way I could think of is to write my own Exception class and Throw that exception. And do this retry logic from My Exception class.
Is there any other better way to this?
class MyClass {
public void method1() {
try {
//do some logic
} catch (Exception e) {
//retry logic
//existing exception handling logic
}
}
public void method2() {
try {
//do some logic
} catch (Exception e) {
//retry logic
//existing exception handling logic
}
}
public void method3() {
try {
//do some logic
} catch (Exception e) {
//retry logic
//existing exception handling logic
}
}
}
EDIT:
class MyClass {
public void method1(int a, int b) {
try {
//do some logic
} catch (Exception e) {
Object args[] = {a,b};
executeLater("method1",args);
//retry logic
//existing exception handling logic
}
}
public void method2() {
try {
//do some logic
} catch (Exception e) {
Object args[] = null;
executeLater("method1",args);
//retry logic
//existing exception handling logic
}
}
public void method3(String abcd, int a) {
try {
//do some logic
} catch (Exception e) {
Object args[] = {abcd,a};
executeLater("method1",args);
//retry logic
//existing exception handling logic
}
}
public boolean executeLater(String methodName, Object args[]){
//Execute given method with the supplied args
return true;
}
}
Added code that shows what i would be doing in each catch clause
boolean processCompleted=false;
while(!processCompleted){
try{
doProcess();
processCompleted=true;
}catch(Exception e){
Thread.sleep(10000);
}
}
This might give you an idea. It keeps try to call doProcess until it doesn't throw exception. If any exception occurs, waits 10 seconds.
Well, you could extract the whole catch block content to a method and call that one, but this only works if your retry logic is not dependent on the specific method. And it also requires a try-catch in every method.
Instead, use functional programming to shorten it:
public class Playground
{
public static void main(String[] args)
{
new Playground().method2(1, 2);
new Playground().method1();
}
public void method1()
{
tryAndTryAgain(() -> {
// logic 1
System.out.println("no params");
throw new RuntimeException();
});
}
public void method2(int a, int b)
{
tryAndTryAgain(() -> {
// logic 2
System.out.println(a + " " + b);
throw new RuntimeException();
});
}
public static void tryAndTryAgain(Runnable tryThis)
{
try
{
tryThis.run();
}
catch (Exception e)
{
new Timer().schedule(new TimerTask()
{
#Override
public void run()
{
tryAndTryAgain(tryThis);
}
}, 1000);
// existing exception handling logic
}
}
}
The exact structure depends on your specfic implementation, but it should give you an idea how to structure it. The benefit is that all those methods can concentrate on the business logic, and the retry logic and exception handling are done in a util method. And that util method doesn't even need to know anything about parameters, methods, or anything, because all the business logic is contained in the Runnable.
I want to throw an exception (any type) in Java, but the restriction is that i can't add " throws Exception " to my main method. So i tried this:
import java.io.IOException;
class Util
{
#SuppressWarnings("unchecked")
private static <T extends Throwable> void throwException(Throwable exception, Object dummy) throws T
{
throw (T) exception;
}
public static void throwException(Throwable exception)
{
Util.<RuntimeException>throwException(exception, null);
}
}
public class Test
{
public static void met() {
Util.throwException(new IOException("This is an exception!"));
}
public static void main(String[] args)
{
System.out.println("->main");
try {
Test.met();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
This code works, but when i am trying to catch an "IOException", for examle, in try-catch block, it doesnt compile. The compiler tells me that IOException is never thrown. It works only for exceptions that extend RuntimeException. Is there a way to solve this?
Added:
import java.io.IOException;
class Util
{
#SuppressWarnings("unchecked")
private static <T extends Throwable> void throwException(Throwable exception, Object dummy) throws T
{
throw (T) exception;
}
public static void throwException(Throwable exception)
{
Util.<RuntimeException>throwException(exception, null);
}
}
public class Test
{
public static void met() { // this method's signature can't be changed
Util.throwException(new IOException("This is an exception!"));
}
public static void main(String[] args)
{
System.out.println("->main");
try {
Test.met();
} catch (IOException e) { // can't be changed and it does not compile right now
System.out.println(e.getMessage());
}
}
}
The simple answer: you can't.
The more complex answer: you can't, and you really shouldn't look to do this. The main reason being, if your code can catch exceptions that it's not advertised to, then that leads to inconsistency and bugs.
Above all, that code block isn't meant to catch anything other than an IOException; that is, the code is only meant to recover on something going haywire with IO. If I were to try and catch anything else, then that would imply that the code knows how to recover from that scenario, which is very much not the case.
As an aside, any children of IOException will be caught by that block, so you don't have to worry about catching FileNotFoundExecption, since that will handle it.
This is awful coding, and I feel dirty just writing it...
Instead of catch-ing the IOException directly, you can check that the caught Exception is an IOException.
public class Test
{
public static void main(String[] args)
{
System.out.println("->main");
try {
Test.met();
} catch (Exception e) {
if (e instanceof IOException) {
System.out.println(e.getMessage());
}
}
}
}
I have a GWT project, in which I have a method like this:
#Override
public void onFailure(Throwable caught)
{
if (caught.getClass()== MyException.class)
{
//do specific stuff
}
else
{
// do generic stuf
}
}
Where MyException is a custom defined exception. A colleague of mine told me, that since this will get converted into JavaScript, where "there are no classes", this is not a very good idea and I should use:
#Override
public void onFailure(Throwable caught)
{
try {
throw caught;
} catch (MyException e) {
//do specific stuff
} catch (Throwable t) {
//do generic stuff
}
}
Since the first way actually works (at least on my side), will there be any problem if I continue to use it, or should I go with the second way?
You can use instanceof operator, it works -
#Override
public void onFailure(Throwable caught)
{
if (caught instanceof MyException)
{
//do specific stuff
}
else
{
// do generic stuf
}
}
I personnally prefer the second way.
Any Exception you do not catch, can be handle by a global UncaughtExceptionHandler.
GWT.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
public void onUncaughtException(Throwable e) {
// TODO Global Exception Handling ...
}
});
May be it could be silly,but I want to clear my the technical understanding of this code:
import netscape.*;//ldap jar
public class A {
public void method() {
...
try {
//code is written here.
LDAPSearchResults lsr = ldi.search(LDAPConnectionInfo.MY_SEARCHBASE,LDAPConnectionInfo.MY_SCOPE,LDAPConnectionInfo.MY_FILTER,null,false);
while(lsr.hasMoreElements()){
LDAPEntry findEntry = (LDAPEntry)lsr.nextElement();
} catch(...) {
}
}
}
Now I call another class
public class B {
A a = new A();
//here I want to use attributeName
}
How could I access A class's member(in try block) in B class.
Any way to handle try block code for reuse in another class.
How could I handle all those exception in another class.
Any modification should I need...
Calling method of Object type.
public class C{
private String attributeName;
public String getAttributeName() {
return attributeName;
}
public Object method(){
attributeName=lAttribute.getName();
}
}
How could print this Object type method into String(in a jsp page)... any inputs
You'll need a member in class A and a getter:
public class A {
private String attributeName;
public String getAttributeName() {
return attributeName;
}
public void method(){
...
try {
//code is written here.
attributeName = lAttribute.getName();
}
catch() {
}
}
}
Then:
public class B {
A a = new A();
// somewhere
String str = a.getAttributeName();
}
There's no way to access a method's private variables like you did in the original example, as they only exist on the stack during the method call.
Edit: I noticed another question:
How could I handle all those exception in another class.
I assume you want to call your method somewhere else and catch the exceptions there. In that case you can use the throws keyword to communicate that your method will pass exceptions to the caller:
public class A {
public void method() throws IOException {
//code is written here.
String attributeName = lAttribute.getName();
}
public void anotherMethod() {
try {
method();
} catch(IOException ex) {
...
}
}
}
then if some other piece of code calls method it will be forced to either handle or further propagate the exception.
How could I handle all those exception in another class.
In your calling class you can catch Throwable (which will catch all exceptions and errors)
try {
....
}
catch (Throwable t) {
//do something with the throwable.
}
if you do not want to catch Errors (Ive only done this when messing around with ImageIO and had memory problems) in Java then catch Exception instead
Any way to handle try block code for reuse in another class
here you could create a method in another class and then call it within your try /catch block
public class XYX {
public void methodForTry() throws Exception {
//do something
}
}
try {
new XYZ().methodForTry();
}
catch (Exception e){
}
You may or may not want to create new XYZ here. It depends what state this object may or may not hold.
As to the last questions I think Tudor's answer covers this
Your question may be about extracting the code template
try { ... do stuff ... }
catch (MyFirstException e) { ...handle ... }
catch (MySecondException e) { ...handle ... }
... more catch ...
Where you only want to change the ... do stuff ... part. In that case you'd need closures, which are coming with Java 8, and today you'd need something quite cumbersome, of this sort:
public static void tryCatch(RunnableExc r) {
try { r.run(); }
catch (MyFirstException e) { ...handle ... }
catch (MySecondException e) { ...handle ... }
... more catch ...
}
where RunnableExc would be an
interface RunnableExc { void run() throws Exception; }
and you'd use it this way:
tryCatch(new RunnableExc() { public void run() throws Exception {
... do stuff ...
}});
why not return it?
public String method() {
String attributeName
try {
//code is written here.
attributeName = lAttribute.getName();
} catch(...) {
}
return attributeName;
}
public class B {
A a = new A();
String attributeName = a.method();
}
I've made an abstract Thread that processes some streams in its run() method. I'd like to be able to have the subclasses handle these exceptions rather than the abstract parent class, but I don't know the most elegant way to do that. Right now, I'm doing something like this:
import org.apache.logging.log4j; // (I use log4j for logging)
public interface Loggable {
Logger getLogger();
}
public abstract class ParentThread extends Thread implements Loggable {
private final static Logger logger =
Logger.getLogger(ParentThread.class); // Logger with no Appenders
#Override
public void run() {
try {
// Do some stuff that throws exceptions
doAbstractStuff();
} catch (SomeSortOfException ex) {
getLogger().error("Oh noes!", ex);
} catch (SomeOtherException ex) {
getLogger().error("The sky is falling!", ex);
}
}
public Logger getLogger() { return logger; }
protected abstract void doAbstractStuff();
}
public class ChildThread extends ParentThread {
#Override
public Logger getLogger() { /* return a logger that I actually use */ }
#Override
public void doAbstractStuff() { /* Implementation */ }
}
I guess I should mention that the ChildThread is actually an inner class of my main form, and that its logger belongs to that form.
Another approach I thought of was to have an
abstract void handleException(Exception ex);
in ParentThread, but then I'm not able to handle individual exceptions from the ChildThread.
Your first solution seems conceptually wrong to me: mixing application-specific error-handling with generic logging.
Your second idea (the callback) seems a better solution and offers the possibility of abstracting away the implementation-specific exceptions for custom events, for example:
public abstract class Parent {
public void run() {
InputStream in = null;
try {
in = new URL("bladiebla").openConnection().getInputStream();
String text = // ...read text from InputStream
if (text == null || text.length() == 0) {
handleMyEvent(new NoInputEvent());
return;
}
doWork(text);
} catch (MalformedURLException e) {
handleMyEvent(new MyEvent(e));
} catch (IOException e) {
handleMyEvent(new MyEvent(e));
}
finally {
if (in != null) {
try {
in.close();
}
catch(IOException e) {
handleMyEvent(e);
}
}
}
}
abstract void doWork(String text);
abstract void handleMyEvent(MyEvent myEvent);
}
public class MyEvent {
private Exception exception;
public MyEvent() {}
public MyEvent(Exception exception) {//set it}
}
public class NoInputEvent extends MyEvent {
}
Well there's no difference between
} catch (SomeSortOfException ex) {
getLogger().error("Oh noes!", ex);
} catch (SomeOtherException ex) {
getLogger().error("The sky is falling!", ex);
}
and
if (ex instanceof SomeSortOfException) {
getLogger().error("Oh noes!", ex);
} else if (ex instanceof SomeOtherException) {
getLogger().error("The sky is falling!", ex);
}
although the latter may require some casting.
Your abstract handleException(Exception ex) idea is sound, I'd go with that. I'd be inclined to not make it abstract, though, and define a sensible default implementation in ParentThread, and allow ChildThread to override it if required.
Why is your base class logging exceptions ? Why not use what the platform provide Thread.setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) and let it do whatever instead of mixing logging w/ your do-stuff component.