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 ....
Related
If a thread is interrupted while inside Object.wait() or Thread.join(), it throws an InterruptedException, which resets the thread's interrupted status. I. e., if I have a loop like this inside a Runnable.run():
while (!this._workerThread.isInterrupted()) {
// do something
try {
synchronized (this) {
this.wait(this._waitPeriod);
}
} catch (InterruptedException e) {
if (!this._isStopping()) {
this._handleFault(e);
}
}
}
the thread will continue to run after calling interrupt(). This means I have to explicitly break out of the loop by checking for my own stop flag in the loop condition, rethrow the exception, or add a break.
Now, this is not exactly a problem, since this behaviour is well documented and doesn't prevent me from doing anything the way I want. However, I don't seem to understand the concept behind it: Why is a thread not considered interrupted anymore once the exception has been thrown? A similar behaviour also occurs if you get the interrupted status with interrupted() instead of isInterrupted(), then, too, the thread will only appear interrupted once.
Am I doing something unusual here? For example, is it more common to catch the InterruptedException outside the loop?
(Even though I'm not exactly a beginner, I tagged this "beginner", because it seems like a very basic question to me, looking at it.)
The idea is that an interrupt should be handled once. If an explicit InterruptedException did not clear the "interrupt" flag then most catchers for InterruptedException would have to explicitly clear that flag. Conversely, you can "unclear" the flag by self-interruption (Thread.currentThread().interrupt()). Java's designers went for the semantics which would save keystrokes most of the time (i.e. you more often want to clear the flag than keep it set).
It shouldn't. This is an unfortunate design flaw that makes relying on interruptions a risky business, as too often library code will catch InterruptedException without resetting the thread's interrupted flag and carry on. If you happen to signal an interruption to your thread when that particular piece of broken library code is running, when your code regains execution control, it'll be left without a clue that the interruption happened.
This only needs to happen once in any place that you're calling from your code, so in order to be able to interrupt a thread and then use the interrupted bit to control your flow from inside said thread safely, you need to be 100% sure that every piece of code that you're calling does not clear the interrupted bit by mistake. This is very hard to do when libraries are involved, but even if you could account for every single library that you're using in your code, that still doesn't account for buggy JRE code that can make the same mistake.
The fact that it only takes one library (or JRE!) author to not care or think about interruptions in order to break the logic of code that requires it shows that this is the wrong default action to take. Someone who doesn't care about the thread's interrupted bit probably won't bother to reset it after catching InterruptedException – maybe they don't even know it exists! If catching InterruptedException didn't reset the thread's interrupted status, then anyone who did not know about the interrupted bit would automatically "do the right thing" and not cause a problem for any calling code relying on interruptions. Anyone who required clearing it could still do so manually, but then it'd be an explicit action which is much more likely to be correct than an usually unintended side-effect of catching the checked InterruptedException exception. As it stands right now, if you rely on the thread's interrupted bit, anyone down your calling stack that calls Thread.sleep() carelessly can potentially ruin your day.
As a result, most Java multi-threaded code will just duplicate the Java thread interrupt model with an "isRunning" instance field and some mechanism to flip it as a workaround.
Write your code like this and you won't need a flag:
try {
while (!this._workerThread.isInterrupted()) {
// do something
synchronized (this) {
this.wait(this._waitPeriod);
}
// do something else
}
} catch (InterruptedException e) {
// ignore ...
}
As #Boyan points out, it is a bad idea to squash that the interrupt exception ... in general. In this case, the context will determine whether you should squash it (as above), set the interrupt flag (again) or allow the exception to propagate. Among other things, it depends on what the interrupt means in / to your application.
That's because an InterruptedException is considered an abnormal event in which someone else tries to stop a thread from outside it.
When you want to really interrupt a thread you just break its loop condition by setting a boolean or something similar. Or you use .wait() and .notify() from inside that thread. But if you are doing wait() externally:
an exception is thrown to notify that an external thread tried to interrupt me or to make me wait
the thread continues its work because it doesn't take any order from another thread! But the raise of the exception allows you to add special handling and do whatever you want, also effectively stop the thread.
my question is simple. How to force JAVA to terminate the program I am writing when any Exception occures?
I am currenlty using Swing and when a NullPointer exception is thrown, the program keeps on running in the background :| While running this way I can only close it from the task manager. The bad thing is that when I run the same program again, a second instance is created and I don't know why, but when I have more than 1 instance of the same program, one time I get null exception, next time not, next time yes, next time not.... Complete randomness.
Thanks in advance!
This article will be of interest wrt. catching exceptions (which, ideally, you should be eliminating).
The idea is that you can plug in a proxy to wrap the invocation of the Swing event, and catch any resultant exceptions. You can then decide what to do - alert someone, exit etc.
Obviously it seems that your program has at least a bug that you can try to iron out with a debugger.
As for your question, an exception will terminate your program if it isn't caught. So if you always throw your exceptions, including in the main method, when one happen will cause the program to exit.
However, as Mac said in the comment
A Swing app has an event loop in the way. The event loop catches Throwable (I believe), so he can't exactly control what's caught in the normal way.
You should fix your bugs in your program. An exception will terminate the program if it isn't caught, you are probably catching the exception. You can always exit a program with System.exit(0);
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
Does throwing an Exception have to cause the program to terminate?
I think its no, I just want to make sure
It depends on the thread where the exception is thrown, and on the other threads running on the same time in the application.
An uncaught exception terminates the thread where it was thrown. If the rest of the threads are only daemon threads, then yes, the application will be terminated.
According to Thread.setDaemon(boolean) documentation:
The Java Virtual Machine exits when the only threads running are all daemon threads.
No, it does not have to cause it to terminate. You could catch the exception and do something useful with it, like show a message to the user that an error occurred and why.
In Java and .NET, if you don't handle an exception, it will most like cause your program to terminate.
Simply throwing an exception will not terminate the program, as such. It is what happens after it was thrown that determines what will occur.
Failing to catch an exception will likely cause the program to terminate, but the act of throwing one will not. At the very least, any application should have some kind of last line of defense for catching all otherwise unhandled exceptions and handling them (even if handling them means, for some at least, throwing them outside of the application and terminating because something external to the application expects this).
Only "Unhandled Exceptions" will cause your program to crash. To handle exceptions you use the following form
try {
// May Throw ApocalypseException
functionThatMightBlowUpTheWorld();
}
catch (ApocalypseException e){
System.err.println("We accidentally almost blew up the world because: ");
System.err.println(e.message);
}
If a thread is interrupted while inside Object.wait() or Thread.join(), it throws an InterruptedException, which resets the thread's interrupted status. I. e., if I have a loop like this inside a Runnable.run():
while (!this._workerThread.isInterrupted()) {
// do something
try {
synchronized (this) {
this.wait(this._waitPeriod);
}
} catch (InterruptedException e) {
if (!this._isStopping()) {
this._handleFault(e);
}
}
}
the thread will continue to run after calling interrupt(). This means I have to explicitly break out of the loop by checking for my own stop flag in the loop condition, rethrow the exception, or add a break.
Now, this is not exactly a problem, since this behaviour is well documented and doesn't prevent me from doing anything the way I want. However, I don't seem to understand the concept behind it: Why is a thread not considered interrupted anymore once the exception has been thrown? A similar behaviour also occurs if you get the interrupted status with interrupted() instead of isInterrupted(), then, too, the thread will only appear interrupted once.
Am I doing something unusual here? For example, is it more common to catch the InterruptedException outside the loop?
(Even though I'm not exactly a beginner, I tagged this "beginner", because it seems like a very basic question to me, looking at it.)
The idea is that an interrupt should be handled once. If an explicit InterruptedException did not clear the "interrupt" flag then most catchers for InterruptedException would have to explicitly clear that flag. Conversely, you can "unclear" the flag by self-interruption (Thread.currentThread().interrupt()). Java's designers went for the semantics which would save keystrokes most of the time (i.e. you more often want to clear the flag than keep it set).
It shouldn't. This is an unfortunate design flaw that makes relying on interruptions a risky business, as too often library code will catch InterruptedException without resetting the thread's interrupted flag and carry on. If you happen to signal an interruption to your thread when that particular piece of broken library code is running, when your code regains execution control, it'll be left without a clue that the interruption happened.
This only needs to happen once in any place that you're calling from your code, so in order to be able to interrupt a thread and then use the interrupted bit to control your flow from inside said thread safely, you need to be 100% sure that every piece of code that you're calling does not clear the interrupted bit by mistake. This is very hard to do when libraries are involved, but even if you could account for every single library that you're using in your code, that still doesn't account for buggy JRE code that can make the same mistake.
The fact that it only takes one library (or JRE!) author to not care or think about interruptions in order to break the logic of code that requires it shows that this is the wrong default action to take. Someone who doesn't care about the thread's interrupted bit probably won't bother to reset it after catching InterruptedException – maybe they don't even know it exists! If catching InterruptedException didn't reset the thread's interrupted status, then anyone who did not know about the interrupted bit would automatically "do the right thing" and not cause a problem for any calling code relying on interruptions. Anyone who required clearing it could still do so manually, but then it'd be an explicit action which is much more likely to be correct than an usually unintended side-effect of catching the checked InterruptedException exception. As it stands right now, if you rely on the thread's interrupted bit, anyone down your calling stack that calls Thread.sleep() carelessly can potentially ruin your day.
As a result, most Java multi-threaded code will just duplicate the Java thread interrupt model with an "isRunning" instance field and some mechanism to flip it as a workaround.
Write your code like this and you won't need a flag:
try {
while (!this._workerThread.isInterrupted()) {
// do something
synchronized (this) {
this.wait(this._waitPeriod);
}
// do something else
}
} catch (InterruptedException e) {
// ignore ...
}
As #Boyan points out, it is a bad idea to squash that the interrupt exception ... in general. In this case, the context will determine whether you should squash it (as above), set the interrupt flag (again) or allow the exception to propagate. Among other things, it depends on what the interrupt means in / to your application.
That's because an InterruptedException is considered an abnormal event in which someone else tries to stop a thread from outside it.
When you want to really interrupt a thread you just break its loop condition by setting a boolean or something similar. Or you use .wait() and .notify() from inside that thread. But if you are doing wait() externally:
an exception is thrown to notify that an external thread tried to interrupt me or to make me wait
the thread continues its work because it doesn't take any order from another thread! But the raise of the exception allows you to add special handling and do whatever you want, also effectively stop the thread.