java ScheduledExecutorService runnable exception handling - java

I am realizing that if a exception are raised inside(or not, but should be related to) my runnable's run method, all my future tasks will not be run.
So my question is: How can I recover from such a exception (where to catch it)?
I have tried this:
ScheduledExecutorService Exception handling
If i do a while loop to catch the exception, the future tasks are still not executed. I also tried to schedule the catch, no help either.
I tried to put a huge try/catch to wrap all the code in run method but it seems to be not catching anything, and some exception are still not catches and causing all my future tasks to not run.

In the executor framework, you are giving control of running a job away from one main application thread to a thread pool thread. A thread submits the work through a schedule, or submit method is returned a Future object that allows it to get information through a get method. The get method will throw an executor exception whose cause is probably the exception that your code inside the runnable threw. If the main thread does not do that it will never see that exception, so it really depends on your application logic flow.
Another thing also to mention, if you try catch all, what do you mean by that if you are doing something similar to
try {
....
}
catch(Exception e) {
.... }
you are really not catching errors in your app (throwable is the father of Exception and Error) so you might have some static initializer error (an exception caught in a static block)
Again it all depends on how you want exception handling to happen you have full power,
Thank you

Related

Does android have any global interface that records each exception in the app?

I want to track all type of exceptions in my Android project avoiding manual collecting exceptions from every catch block.
Does android have any such global interface that can capture information of every exception of application? I would like to track every exception in a single line.
If you are okay with the app crashing on every exception, you can set a handler for uncaught exceptions on the current Thread like this:
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread thread, Throwable throwable) {
// your exception handling code here
}
});
If you use AsyncTasks or other Threading methods in your app, you have to do this on every new thread.
This method is normally used to write your own error reporting, maybe it's not exactly what you want to do.
If you don't want that your app crashes, I think you have to implement something on your own that is easily callable from within catch blocks.
Is it android have any such global interface who capture information of every exception of application,so that i would track every exception in a single line?
No there is not.
Exceptions are either checked or unchecked. You 'must' catch checked-exceptions using try-catch or throws unless the code wont compile.
Any uncaught exception is handled in unCoughtExceptionHandler object of the Thread which exception uccored in.
Not that I know of. If there was though, I'm sure no one would be using try catch blocks, and it would be a well known process/method. You can, though, debug with android studio.
Only thing I can think of that is similar could be setting a common handler to catch exceptions:
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
And the method that goes with that annonymous inner class is:
public void uncaughtException(Thread thread, Throwable throwable) {
Where you put your exceptions. I found an example on tutorialspoint.com, and edited a screen shot to make it clearer:
Then, you can notice that we purposely throw that runTimeException after starting the thread. So, result will be:
Thread[Thread-0,5,main] throws exception: java.lang.RuntimeException

Thread.stop() and finally [duplicate]

This question already has answers here:
Are Thread.stop and friends ever safe in Java?
(8 answers)
Closed 7 years ago.
I created a following Class named as ThreadClass (which is a thread as you can see),its structure is something like the following
class SomeTask implements Runnable
{
boolean someCondition=true;
public void run() {
try
{
while(someCondition)
{
//Here goes the Process Code
}
}
catch(Exception errorException)
{
//Catching the Exception
}
finally
{
////I expect that this finally should run every time ,whatever happens in the world
}
}
}
My question is about the finally block and the stop() method
As above class is implementing Runnable, so I can create the object of this class and start a thread of it by calling start() method.I am also aware of the fact that I can stop this thread by using stop() (Yes , I know it is deprecated) method .
What I want to clarify myself is that, if somehow I need to call the stop method on the ThreadClass's object, then can I rely on the finally block to execute even if the thread is stopped by calling stop() as I am doing some important closing things in the finally block.
Thread#stop works by throwing a ThreadDeath exception, it doesn't obliterate the thread instantaneously the way System.exit blows away the JVM. ThreadDeath can even be caught, although that's not a good idea. So try blocks are still relevant.
However, complicating this is that if the thread has stop called on it multiple times then, if the second stop is called when the thread is in a finally block then it could be thrown from the finally block so that the finally block would not complete then. And if the thread's cleanup takes a while then it might be likely that stop could be called more than once on it.
Or even if you only call stop once, if at the time that stop is called the thread happens to be already executing its finally block, then the stop would interfere with completing the finally block.
This is similar to what the technotes on Thread primitive deprecation point out:
1) A thread can throw a ThreadDeath exception almost anywhere. All synchronized methods and blocks would have to be studied in great detail, with this in mind.
2) A thread can throw a second ThreadDeath exception while cleaning up from the first (in the catch or finally clause). Cleanup would have to repeated till it succeeded. The code to ensure this would be quite complex.
So there are some cases that are problematic, it would be very difficult to make sure cleanup gets done properly. James' comment is correct, if at all possible you should use interruption for this kind of thing so that the thread can reliably finish its business.

Java Exception handling mechanism

In Java,If I didn't catch the thrown Exception then the Thread execution stops there else if I catch the same then the Thread execution continues after the catch block.Why Java Exception handling designed in this way.
Thx
The purpose of an exception is to let the program understand that Something Weird Has Happened, and so doing what would ordinarily be next in the program is very likely to be wrong. A function you called couldn't give you a real answer, and you were relying on that answer, so it had to stop you.
There are two ways this can end: you handle the exception (via a catch block), or the entire program stops.
If your program doesn't know what to do when these things happen, it's best to do nothing. Let the Exception crash the thread, and then you can check the crash log later, and find out exactly what crashed the program and why. If your program can't handle an error, the Exception's "crash the thread" behavior lets you see what error was unhandled, so you can change the program to make it able to handle this kind of situation in the future, or prevent the situation from occuring.
Some errors might be pretty normal, though, and shouldn't stop the entire program- you need to have a way to recover from them. That's what a catch block is for: a chance to say "Hello Java, I know just what to do about this problem", and then do it. A Catch block lets you clean up the program and move on, if you can. Java assumes your Catch block deals with the problem and makes it go away. If there's a new problem, or for that matter the same one, you need to throw the caught exception again, or maybe a new one, so something else can try to fix the problem- even if that something else is you, as a programmer.
If exceptions always crashed the program, there would be no way to handle errors that are expected and can be dealt with. But if absolutely nothing is ready to handle the error, the program can't keep running, because now something's gone weird and it doesn't know what to do because you didn't program it to do anything.
In Java,If I didn't catch the thrown Exception then the Thread execution stops there else if I catch the same then the Thread execution continues after the catch block.
There is a third case. If the thread has an Thread.UncaughtExceptionHandler (registered by calling thread.setUncaughtExceptionHandler(handler)), then it will be notified in the event of an uncaught exception on the thread stack ... before the thread exits. (In fact, the behaviour is a bit more complicated than this; see the javadocs.)
Why Java Exception handling designed in this way.
Because the alternative is far worse ... in most cases.
Assuming that the thread has caused the run() method to terminate ('cos you didn't catch the exception), then the only thing you could do "not stop" would be have the thread infrastructure call run() again.
But the uncaught exception typically means something BAD has happened. Typical run() methods are not designed so them multiple times will do something sensible. And if the run() method just failed for some unknown reason (as far as the run() method is concerned), it is even less likely that calling it again will work.
Besides, in the few cases where it is sensible for your run() method to catch and resume from every exception, you can always code it to do that. And if you don't want to the thread to resume, you can implement an "uncaught exception handler" to do notify something else and (maybe) start higher level recovery.
The only thing that is maybe slightly questionable about the current design is that Thread termination due to an uncaught exception is often silent. But the cure for that is to implement a default uncaught exception handler that makes some noise ....

sleep from main thread is throwing InterruptedException

I have the main thread of execution which spawns new threads. In the main thread of execution in main() I am calling Thread.sleep(). When do I get an Unhandled exception type InterruptedException?.
I am unsure of why am I getting this. I thought this was because I needed a reference to the main thread so I went ahead and made a reference to it via Thread.currentThread().
Is this not the way to have the thread sleep? What I need to do is have the main thread wait/sleep/delay till it does it required work again.
What you see is a compilation error, due to the fact that you didn't handle the checked exception (InterruptedException in this case) properly. Handling means doing one of the following:
1) Declaring the method as throws InterruptedException, thus requiring the caller to handle the exception
2) Catching it with a try{..}catch(..){..} block. For example:
try {
Thread.sleep(1500);
} catch(InterruptedException e) {
System.out.println("got interrupted!");
}
InterruptedException is used to indicate that the current thread has been interrupted by an external thread while it was performing some blocking operation (e.g. interruptible IO, wait, sleep)
At the line where you're definition of main starts, just include throws Exception. I too was facing similar problem, and this helped. After this inclusion, you need not include the Thread.sleep(xx); inside a try-catch statement
Thread.sleep(t);
This is how you can make your thread wait. where t is in milliseconds.
It is working fine in my main method, so to find out your problem it would be better if you can provide your code here.

Unhandled exceptions with Java scheduled executors

I have the following issue and I would like to know what exactly happens. I am using Java's ScheduledExecutorService to run a task every five minutes. It works very well. Executors completely changed the way I do thread programming in Java.
Now, I browsed Java Doc for information about what would be the behavior in case the scheduled task fails with an unhandled exception, but couldn't find anything.
Is the next scheduled task still going to run? If there is an unhandled exception, the scheduled executor stops scheduling task? Can anyone point to information regarding this simple issue?
Thanks a lot.
The Javadoc of both scheduleAtFixedRate and scheduleWithFixedDelay says "If any execution of the task encounters an exception, subsequent executions are suppressed." I don't find that to be exactly crystal clear, but it seems to be saying that if your run method throws any kind of exception, then the scheduler will effectively drop that task. Any other tasks running via that scheduler should not be affected. It shouldn't be hard to test what it actually does...
Cancellation of the task may not necessarily be a bad thing. If the run method throws a RuntimeException, it's probably got a bug somewhere, and the state of the system is unknown. But at minimum I would advise catching RuntimeException in your run method, and logging the full stack trace at SEVERE. You may want to then rethrow to cancel the task, depending on the circumstances. But either way you'll need the logging to have a fighting chance of working out what went wrong.
If you are using scheduleAtFixedRate() or scheduleAtFixedDelay(), and your task bails out with an exception, that task will not be rescheduled. However, other independent tasks should continue to execute as expected. (See API Docs). If you care that this has happened, you can grab ahold of the ScheduledFuture that is returned and call the get() method. If the underlying task tosses an exception, you'll get it thrown out of the get() method, wrapped in an ExecutionException.
This man had the same problem.
http://code.nomad-labs.com/2011/12/09/mother-fk-the-scheduledexecutorservice/
His solution is to catch Exception inside the runnable and re throw an RuntimeException:
try {
theRunnable.run();
} catch (Exception e) {
// LOG IT HERE!!!
System.err.println("error in executing: " + theRunnable + ". It will no longer be run!");
e.printStackTrace();
// and re throw it so that the Executor also gets this error so that it can do what it would
// usually do
throw new RuntimeException(e);
}
It looks like the API doesn't define any specific exception handling mechanism. I.e. uncaught exception just pops through the thread frames and eventually is being logged to stderr.
I see that you can exploit the following exception handling strategies:
define handler at the class of the task which objects are submitted to thread pool;
provide your own ThreadFactory implementation to thread pool that initializes default handler via setUncaughtExceptionHandler() or ThreadGroup's uncaughtException();

Categories