Make my java application shut down if it stops working - java

Is there a way to make my java application shut down there is an error? e.g. if I have a nullpointerexception, can I just make it completely close out?

Any uncaught exception at the top level will automatically halt the thread it's in. If you have more than one thread in your program, the other threads will still survive. If you want to terminate explicitly, you can call System.exit()

You can use System.exit(0); to terminate the JVM.
However, you should avoid NullPointerException by checking the reference before using it:
if(foo != null) foo.doSomething();

As others have said, catching the exception and calling System.exit() is (generally) the right approach. But there is more to it than that:
Q: Do I really need to catch it?
A: If your application is a conventional command-line application, and the exception is thrown on the "main" thread, then you may not need to catch it. Uncaught exceptions on the main thread will cause the application to exit ... if there are no other non-daemon threads in existence. (In fact, the same thing goes for any thread ... )
However if your thread has more than one non-daemon thread, then you need to do something to stop the application. Like catch the exception and call exit().
Q: Where do you catch it?
A: On the stack of any thread where the "fatal" exception might be thrown. There are two ways to do this:
Put a try / catch (Throwable) in the main(String[]) method, a thread's run() method, etcetera.
Install a default uncaught exception handler.
What you DON'T want to do is to add System.exit() calls all through your codebase. That approach leads to all sorts of problems with reusability, unit testing and generally figuring out "why has the effing application died again".
Q: What if it is already caught?
A: One reason why your application might not be exiting naturally, is that your code is already catching the exception ... by accident. For instance:
try {
doSomething()
} catch (Exception ex) {
handle an IO exception
}
In the above, some ignorant / lazy programmer hasn't bothered to consider the exceptions that might be thrown in doSomething and has assumed that they are all some kind of IO related exception. But if the exception was actually an unexpected NullPointerException ... or something worse ... then the code has just squashed it.
The cure for this kind of thing is code-reviews and mentoring to cure the programmer of his bad habits ... hopefully before he does too much damage to the codebase! And if you find this kind of thing in your codebase, you should fix it immediately ... and probably "grep" for similar occurrences and fix them too.

Related

Interrupted Exception Error in Java for Exception [duplicate]

What is the difference between the following ways of handling InterruptedException? What is the best way to do it?
try{
//...
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
}
OR
try{
//...
} catch(InterruptedException e) {
throw new RuntimeException(e);
}
EDIT: I'd like to also know in which scenarios are these two used.
What is the difference between the following ways of handling InterruptedException? What is the best way to do it?
You've probably come to ask this question because you've called a method that throws InterruptedException.
First of all, you should see throws InterruptedException for what it is: A part of the method signature and a possible outcome of calling the method you're calling. So start by embracing the fact that an InterruptedException is a perfectly valid result of the method call.
Now, if the method you're calling throws such exception, what should your method do? You can figure out the answer by thinking about the following:
Does it make sense for the method you are implementing to throw an InterruptedException? Put differently, is an InterruptedException a sensible outcome when calling your method?
If yes, then throws InterruptedException should be part of your method signature, and you should let the exception propagate (i.e. don't catch it at all).
Example: Your method waits for a value from the network to finish the computation and return a result. If the blocking network call throws an InterruptedException your method can not finish computation in a normal way. You let the InterruptedException propagate.
int computeSum(Server server) throws InterruptedException {
// Any InterruptedException thrown below is propagated
int a = server.getValueA();
int b = server.getValueB();
return a + b;
}
If no, then you should not declare your method with throws InterruptedException and you should (must!) catch the exception. Now two things are important to keep in mind in this situation:
Someone interrupted your thread. That someone is probably eager to cancel the operation, terminate the program gracefully, or whatever. You should be polite to that someone and return from your method without further ado.
Even though your method can manage to produce a sensible return value in case of an InterruptedException the fact that the thread has been interrupted may still be of importance. In particular, the code that calls your method may be interested in whether an interruption occurred during execution of your method. You should therefore log the fact an interruption took place by setting the interrupted flag: Thread.currentThread().interrupt()
Example: The user has asked to print a sum of two values. Printing "Failed to compute sum" is acceptable if the sum can't be computed (and much better than letting the program crash with a stack trace due to an InterruptedException). In other words, it does not make sense to declare this method with throws InterruptedException.
void printSum(Server server) {
try {
int sum = computeSum(server);
System.out.println("Sum: " + sum);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // set interrupt flag
System.out.println("Failed to compute sum");
}
}
By now it should be clear that just doing throw new RuntimeException(e) is a bad idea. It isn't very polite to the caller. You could invent a new runtime exception but the root cause (someone wants the thread to stop execution) might get lost.
Other examples:
Implementing Runnable: As you may have discovered, the signature of Runnable.run does not allow for rethrowing InterruptedExceptions. Well, you signed up on implementing Runnable, which means that you signed up to deal with possible InterruptedExceptions. Either choose a different interface, such as Callable, or follow the second approach above.
Calling Thread.sleep: You're attempting to read a file and the spec says you should try 10 times with 1 second in between. You call Thread.sleep(1000). So, you need to deal with InterruptedException. For a method such as tryToReadFile it makes perfect sense to say, "If I'm interrupted, I can't complete my action of trying to read the file". In other words, it makes perfect sense for the method to throw InterruptedExceptions.
String tryToReadFile(File f) throws InterruptedException {
for (int i = 0; i < 10; i++) {
if (f.exists())
return readFile(f);
Thread.sleep(1000);
}
return null;
}
This post has been rewritten as an article here.
As it happens I was just reading about this this morning on my way to work in Java Concurrency In Practice by Brian Goetz. Basically he says you should do one of three things
Propagate the InterruptedException - Declare your method to throw the checked InterruptedException so that your caller has to deal with it.
Restore the Interrupt - Sometimes you cannot throw InterruptedException. In these cases you should catch the InterruptedException and restore the interrupt status by calling the interrupt() method on the currentThread so the code higher up the call stack can see that an interrupt was issued, and quickly return from the method. Note: this is only applicable when your method has "try" or "best effort" semantics, i. e. nothing critical would happen if the method doesn't accomplish its goal. For example, log() or sendMetric() may be such method, or boolean tryTransferMoney(), but not void transferMoney(). See here for more details.
Ignore the interruption within method, but restore the status upon exit - e. g. via Guava's Uninterruptibles. Uninterruptibles take over the boilerplate code like in the Noncancelable Task example in JCIP ยง 7.1.3.
What are you trying to do?
The InterruptedException is thrown when a thread is waiting or sleeping and another thread interrupts it using the interrupt method in class Thread. So if you catch this exception, it means that the thread has been interrupted. Usually there is no point in calling Thread.currentThread().interrupt(); again, unless you want to check the "interrupted" status of the thread from somewhere else.
Regarding your other option of throwing a RuntimeException, it does not seem a very wise thing to do (who will catch this? how will it be handled?) but it is difficult to tell more without additional information.
The correct default choice is add InterruptedException to your throws list. An Interrupt indicates that another thread wishes your thread to end. The reason for this request is not made evident and is entirely contextual, so if you don't have any additional knowledge you should assume it's just a friendly shutdown, and anything that avoids that shutdown is a non-friendly response.
Java will not randomly throw InterruptedException's, all advice will not affect your application but I have run into a case where developer's following the "swallow" strategy became very inconvenient. A team had developed a large set of tests and used Thread.Sleep a lot. Now we started to run the tests in our CI server, and sometimes due to defects in the code would get stuck into permanent waits. To make the situation worse, when attempting to cancel the CI job it never closed because the Thread.Interrupt that was intended to abort the test did not abort the job. We had to login to the box and manually kill the processes.
So long story short, if you simply throw the InterruptedException you are matching the default intent that your thread should end. If you can't add InterruptedException to your throw list, I'd wrap it in a RuntimeException.
There is a very rational argument to be made that InterruptedException should be a RuntimeException itself, since that would encourage a better "default" handling. It's not a RuntimeException only because the designers stuck to a categorical rule that a RuntimeException should represent an error in your code. Since an InterruptedException does not arise directly from an error in your code, it's not. But the reality is that often an InterruptedException arises because there is an error in your code, (i.e. endless loop, dead-lock), and the Interrupt is some other thread's method for dealing with that error.
If you know there is rational cleanup to be done, then do it. If you know a deeper cause for the Interrupt, you can take on more comprehensive handling.
So in summary your choices for handling should follow this list:
By default, add to throws.
If not allowed to add to throws, throw RuntimeException(e). (Best choice of multiple bad options)
Only when you know an explicit cause of the Interrupt, handle as desired. If your handling is local to your method, then reset interrupted by a call to Thread.currentThread().interrupt().
To me the key thing about this is: an InterruptedException is not anything going wrong, it is the thread doing what you told it to do. Therefore rethrowing it wrapped in a RuntimeException makes zero sense.
In many cases it makes sense to rethrow an exception wrapped in a RuntimeException when you say, I don't know what went wrong here and I can't do anything to fix it, I just want it to get out of the current processing flow and hit whatever application-wide exception handler I have so it can log it. That's not the case with an InterruptedException, it's just the thread responding to having interrupt() called on it, it's throwing the InterruptedException in order to help cancel the thread's processing in a timely way.
So propagate the InterruptedException, or eat it intelligently (meaning at a place where it will have accomplished what it was meant to do) and reset the interrupt flag. Note that the interrupt flag gets cleared when the InterruptedException gets thrown; the assumption the Jdk library developers make is that catching the exception amounts to handling it, so by default the flag is cleared.
So definitely the first way is better, the second posted example in the question is not useful unless you don't expect the thread to actually get interrupted, and interrupting it amounts to an error.
Here's an answer I wrote describing how interrupts work, with an example. You can see in the example code where it is using the InterruptedException to bail out of a while loop in the Runnable's run method.
I just wanted to add one last option to what most people and articles mention. As mR_fr0g has stated, it's important to handle the interrupt correctly either by:
Propagating the InterruptException
Restore Interrupt state on Thread
Or additionally:
Custom handling of Interrupt
There is nothing wrong with handling the interrupt in a custom way depending on your circumstances. As an interrupt is a request for termination, as opposed to a forceful command, it is perfectly valid to complete additional work to allow the application to handle the request gracefully. For example, if a Thread is Sleeping, waiting on IO or a hardware response, when it receives the Interrupt, then it is perfectly valid to gracefully close any connections before terminating the thread.
I highly recommend understanding the topic, but this article is a good source of information: http://www.ibm.com/developerworks/java/library/j-jtp05236/
I would say in some cases it's ok to do nothing. Probably not something you should be doing by default, but in case there should be no way for the interrupt to happen, I'm not sure what else to do (probably logging error, but that does not affect program flow).
One case would be in case you have a task (blocking) queue. In case you have a daemon Thread handling these tasks and you do not interrupt the Thread by yourself (to my knowledge the jvm does not interrupt daemon threads on jvm shutdown), I see no way for the interrupt to happen, and therefore it could be just ignored. (I do know that a daemon thread may be killed by the jvm at any time and therefore are unsuitable in some cases).
EDIT:
Another case might be guarded blocks, at least based on Oracle's tutorial at:
http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html

how to catch all uncaught exceptions from different threads in one place during development?

I have a not small multiple threads application with GUI and socket communications. During the development, I found sometimes there are some exceptions are not caught and logged. I have to stare at the console to get them if there is any.
Is there a way to catch those uncaught exceptions from different threads (including EDT) in one place, saying in main(), and log them? I do put a try-catch in main() to catch the Throwable but it doesn't work.
EDIT:
More specific, I have Executors.newCachedThreadPool() with Runnables. I don't want to use Callable in many cases because I don't want to block my calling thread. Then how can I catch exceptions from those Runnables?
And also how can I catch uncaught exception from the Swing EDT?
I would propose to set a custom handler of type UncaughtExceptionHandler for non-caught exceptions using method Thread.setDefaultUncaughtExceptionHandler. This handler will be invoked by JVM when thread is about to terminate due to an uncaught exception.
Thread.setDefaultUncaughtExceptionHandler((Thread t, Throwable e) -> {
System.out.println(t + " throws exception: " + e);
});
UPD:
As for Swing EDT case, I think there is nice answer here.
Not a simple problem in a large complex program because there is no way to catch an exception in a different thread from the one that threw it. You will have to make sure that every thread in the program has a handler that will catch all exceptions, and report them.
That's easy enough if you control the code that creates all of the threads, but harder if you call library routines that create threads on your behalf. If you're lucky, the libraries will let you provide a ThreadFactory, thus allowing your code to gain control whenever they create a new thread.
Even if you can make sure that every thread has an uncaught exception handler that does the right thing, you still might have some code hiding somewhere (maybe in some 3rd-party library that you call) that catches an exception and ignores it.
Good luck!

Java: closing my app with an exception

I want an app that throws an exception from a button.
The exception should then shutdown the application (unhandled exception).
( I need that to check my code in Runtime.getRuntime().addShutDownHook() )
So I wrote this
button1.addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent e) {
throw new NullPointerException("");
}
});
And tried also tried throwing a RuntimeException, but the application did not close.
Any suggestion how can I close my app due to an exception?
Thanks.
EDIT
I will explain -
In the Java docs - http://docs.oracle.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)
it is noted that when you write a JVM shut down hook - make it a fast running piece of code. Quote:
"Shutdown hooks should also finish their work quickly...."
My code is running a bit longer and I wanted to test it by an exception (and not System.exit() - though it should be the same, but sometimes the results are not the same)
Just wondered how you throw an exception from a button (I know the code is bad, it's for testing ).
check this answer:
How do I catch this exception in Swing?
In implementation of uncaughtException just exit your app.
You need to catch the exception and call System.exit()
It is explained here in the comments (suggested by Duncan Jones ;)
The setDefaultUncaughtExceptionHandler will only work if the thread die (thread abruptly terminates due to an uncaught exception). But EventQueue thread will never die unless the application ends. Therefore without special handling all uncaught exception will be swallow by EventQueue and go into system out silently.
So I would add an uncaught exception handler to trap when other threads die, but to check exceptions throw in the EDT, you have to catch them yourself.
any suggestion how can I close my app due to an exception?
For a start, throwing an exception from the action listener won't work. It will kill the Swing event dispatcher thread, but that won't make the application exit.
The simple solution is to call System.exit(...) from the listener to tell the JVM to shutdown. However, if that approach is a bit "brutal" and may cause tasks being performed asynchronous to be abandoned. You can ameliorate by using shutdown hooks to give the tasks to bail out, but it is still not nice. For instance, shutdown hooks don't fire in a predictable order ...
A better solution is to design your application to attempt to perform an orderly shutdown before it pulls the plug by calling System.exit(). For instance, once the "main" thread has launched the Swing dispatcher event thread, it could wait on a condition which tells it to shutdown. The action listener for the "exit" button would signal this condition, and the main thread would wake up and start shutting things down.

Java: printing to file when you can't use "throw exception"

I have a class for threads (implements runnable). I want to be able to print text to a file inside the method "run", but I can't add "throws IOException" because run() is an implementation of a method in runnable.
Of course there's no way I'll use a gazillion "Try-Catch" in run()...
Thanks
Dealing with checked exceptions in your run() method is tricky for the following reasons:
As #kenson john says (and you observed) you can't simply let them propagate, because run() is not declared as throwing checked exceptions.
If you catch them and rethrow them wrapped in unchecked exceptions, they are likely to go unnoticed by the main thread. Why? Because the exceptions are thrown on the stack of the child thread. Unless they are caught in the run() method, they will be dealt with by the thread's UncaughtExceptionHandler object ... which is likely to be the default handler ... which writes a stacktrace to System.err and then discards the exception.
Now you can set another UncaughtExceptionHandler object for the child thread, or even set a default UncaughtExceptionHandler for the JVM. But what should the handler do? Ideally, the exception needs to be reported back to the main thread (or whatever) to take executive action. But there's no way that the child thread, or a handler for that thread can throw an exception on the main thread's stack. (The best you could do to get the main thread's attention would be to set a flag or call Thread.interrupt() on the main thread ... and hope that it checks the flag / interrupt status periodically.)
Any IOException that is thrown while writing to an output file indicates that something serious has gone wrong; e.g. the file system is full, or the socket or pipe you were writing to is broken / closed. So simply ignoring it could be a big mistake. (For instance, suppose that the file is precious, and that the last thing that the application does is to delete the old version of the file and replace it with the new version we just created. Ooops! We didn't notice that the FS filled up, the new version of the file is corrupt and we just deleted the old version.)
In the light of this, the PrintStream approach is simplest. A PrintStream will quietly catch any IOException that occurs while writing, but record the fact that an exception has occurred. So when the main thread decides that everything should have finished writing, it needs to call PrintStream.checkError() to test if any errors have occurred. (Unfortunately, the API does not allow you to find out what the actual exception was.)
You could wrap the output with a PrintStream, it never throws exceptions.
If you want to do a particular I/O operation in many places without putting each one in an exception handler, just create a function with an exception handler (i.e. it doesn't throw). Then call the non-throwing function to do all your I/O.
I understand why you want to do this, but I think it is a bad practice to throw and catch an exception from run() (which is impossible for the reason mentioned below).
An exception generated from run() would be considered as an "Unchecked" exception in Java. This kind of exception should not be caught by the programmer, and should be taken care of by the VM.
Unchecked exception generally happen at runtime, example: NullPointerException, IllegalStateException.
IOException being a subclass of java.lang.Exception is considered a Checked Exception, therefore should be handled using a try catch within run() or in a method invoked by run().

Java: Is catching exceptions asynchronous?

I am asking because if it is not, it can be abused as synchronizations mechanism. I am asking about Java.
I'm not sure what you mean by "can be abused as synchronizations mechanism" - that doesn't make sense.
Exceptions are per thread - when an exception is thrown, the current thread's execution jumps to the place where the exception is caught. If it's not caught at all, the thread dies. Other threads are not affected.
JLS 11.3.2 Handling Asynchronous Exceptions
Most exceptions occur synchronously as a result of an action by the thread in which they occur, and at a point in the program that is specified to possibly result in such an exception. An asynchronous exception is, by contrast, an exception that can potentially occur at any point in the execution of a program.
Proper understanding of the semantics of asynchronous exceptions is necessary if high-quality machine code is to be generated.
Asynchronous exceptions are rare. They occur only as a result of:
An invocation of the stop methods of class Thread or ThreadGroup
An internal error in the Java virtual machine
So no, while rare, not all Exception handling is synchronous.
No, it's synchronous.
Try stepping through your code with a debugger, you'll see that it executes line after line, and will not continue if you break inside the catch.
Exceptions occur during the execution of a thread. It does not make sense to have an asynchronous catch because the thread has to handle the exception. It cannot proceed till the exception is caught and taken care of. If the exception is not caught or thrown, the thread does not know what it has to do and simple dies and the program may/may not misbehave.
A thread throwing an exception and then proceeding without waiting for the catch does not make sense.
To answer your question, no catching is not asynchronous for all practical purposes.

Categories

Resources