Why is a try catch statement required? [duplicate] - java

This question already has answers here:
Why do I need to handle an exception for Thread.sleep()?
(3 answers)
Closed 4 years ago.
Why is a try/catch exception handling statement required in Java for the below line:
TimeUnit.MILLISECONDS.sleep(250);
I just want my code to sleep for 250 milliseconds before executing the next line. Why is a try-catch statement required? I can’t forsee any exceptions with this. The sleep function in python doesn't require a try catch.
The exception I get in the IDE without adding the try catch is:
Error:(124, 40) error: unreported exception InterruptedException; must be caught or declared to be thrown
When I surround it in the try catch as per below it works fine:
try {
TimeUnit.MILLISECONDS.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}

You need to catch the exception simply because the thread running (sleeping) might be interrupted and you need to catch the interruption.
From the Oracle description of the InterruptedException
Thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity.

Interrupting a thread that is sleeping is a very important part of Java. It provides control when you need to stop an application (or a process) and do not want to be halted from doing so due a thread sleeping. The InterruptException allows developers to catch interrupt attempts and deal with it.
Maybe your beef is with checked exceptions in general.... which is a feature of Java that many people do not like. We can understand your frustration with checked exceptions. You can read up more on checked exceptions in Java via Google.

Related

Abnormal termination in catch block? [duplicate]

This question already has answers here:
Java - shutting down on Out of Memory Error
(9 answers)
Closed 6 years ago.
I'm working on a simple application and now I'm not quite sure how to deal with errors occured while executing application. I'm particularly worried about OutOfMemoryError. Example:
try{
while(true){
//do some job
}
} catch (Exception e){
System.out.println("Exception occured");
} catch (Throwable t){
//log entry of abnormal termination
System.exit(1);
} finally {
//Terminate application normally
}
Is it a correct way to deal with such situation? I mean to attempt to terminate application normally in finally block and just kill JVM in catch(Throwable t).
The issue is finally will never be executed if, say, OutOfMemoryError was thrown.
I don't think that's even needed, if you want to kill your JVM on OutOfMemoryException, you can include some JVM flags:
-XX:OnOutOfMemoryError="kill -9 %p"
It may be possible to free up some memory when hitting OutOfMemoryException depending on what you're doing and it's probably better to explicitly try and catch OutOfMemoryException rather than catching Throwable which includes everything that can be thrown.
If it is a single threaded application, you could just log the OOM, and let the VM finish normally, don't invoke the System.exit(). If it is multi-threaded application, you need to have a policy of shutting it down. In every scenario it is up to you which resources and how should be handled when you need to shutdown your application. You are worried about finally not invoking after System.exit(), if you have more threads they will be killed and you have no control when, they also wouldn't have chance for any finaliztion. If you would like to shutdown your app gracefully then you need to program it in such way to have the logic that does this.
If you call System.exit(...) in a catch block for some exception then a finally block will not be executed if the exception is caught.
Assuming that is what you want to happen ... then you have coded your exception handling correctly.
Is that the "correct" way to deal with this? Well, if this is what you want to happen (i.e. if you want any Error exceptions to cause the normal termination logic to be skipped) then it is correct. But ultimately, you need to decide for yourself.
Having said that, if you are concerned that your application won't be able to perform the termination because it is out of memory, then you could do something like this:
try {
int[] reserved = new int[1,000,000];
while(true){
//do some job
}
} catch (Exception e){
System.out.println("Exception occured");
} catch (Throwable t){
//log entry of abnormal termination
}
// Terminate application normally << HERE
If the JVM throws OOME, when you reach the "HERE" point, there will be a 8MB of reclaimable garbage in the heap. If the termination code fills the heap (again) then the GC will reclaim that garbage and there should be enough space to complete the termination.

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.

Why a thread would interrupt another thread [duplicate]

This question already has answers here:
What kind of behaviour causes an interrupted exception?
(7 answers)
Closed 9 years ago.
In Java multi threaded applications, we deal with InterruptedThreadException. This Exception is thrown if another thread interrupts the current thread. Now what is the reason another thread might want to interrupt the current thread when it knows that it is going to cause an Exception?
Many reasons. But the most popular one is to cancel some task on a thread.
See http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html for details.
In most cases, to notify that a Thread should abort. Usually, a worker thread executing some sort of batch operation is implemented in a way that it terminates itself (i.e. exit out of its run() method) when interrupted.
Unfortunately, a lot of programmers simply catch and swallow it which is a very very bad practice. If a Thread is not expecting an InterruptedException it should either re-throw or should restore its interrupted status if it cannot throw it (if restrained by an Interface for example) by calling
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}

java ScheduledExecutorService runnable exception handling

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

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 ....

Categories