This is a minor annoyance I have when debugging with Eclipse. With "Suspend execution on uncaught exceptions" checked, the debugger will normally suspend a thread right where the exception was thrown. Exceptions on the Event Dispatch Thread, however, cause it to pause on the last line of EventDispatchThread.run(). There is no useful information about what the exception is or what caused it until I resume the thread to allow the stack trace to print to the console.
Debug the following code in Eclipse to demonstrate:
public class SuspendOnUncaughtTest {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
((Object) null).toString();
}
});
}
}
And here is what it looks like after the exception is thrown:
EDIT 10/21/2011: I guess there's nothing weird going on with Eclipse or the Java debugger, it's just that exceptions are caught and rethrown in EventDispatchThread.pumpOneEventForFilters(int). I suppose there's no way to tell Eclipse to "suspend execution on exceptions that are going to be caught and possibly rethrown". Too bad.
Is see a similar result in NeteBeans, but Thread.setDefaultUncaughtExceptionHandler() may be useful in this context. There's an example here.
As far as I can tell, there is no solution to this. Eclipse is behaving correctly, the correct behavior is just annoying.
I had this issue and found something that worked for me.
I am using Kepler, and was able to stop this by going to the breakpoints tab of the debugger perspective and deselecting the checkbox on the EventDispatchThread.
Related
I was tasked with tearing down a Dev environment and setting it up again from scrap to verify our CI-CD processes; only problem was that I messed up creating one topic and so the Kafka Streams application exited with an error.
I dug into it and found the issue and corrected it but as I was digging in I ran into another odd little problem.
I implemented a Unexpected Exception handler as so:
streams.setUncaughtExceptionHandler((t, e) -> {
logger.fatal("Caught unhandled Kafka Streams Exception:", e);
// Do some exception handling.
streams.close();
// Maybe do some more exception handling.
// Open a lock that is waiting after streams.start() call
// to let application exit normally
shutdownLatch.countDown();
});
Problem is that if the application threw an exception because of a topic error when the KafkaStreams::close is call the application seems to dead lock in WindowsSelectorImpl::poll after attempting a call to KafkaStreams::waitOnState.
I thought it might be an issue with calling KafkaStreams::close inside the Exception Handler but I found this SO and a comment from Matthias J. Sax that said it should be ok to call KafkaStreams::Close in the exception handler with the caveat of not calling KafkaStreams::close from multiple threads.
The issue is that I want to implement a shutdown hook to kill the steams application gracefully on request, as well as implement the UnexpectedException handler to clean up and terminate gracefully in the event of exceptions.
I came up with the following solution that checks the KafkaStreams state before calling close and it does actually work, but it seems a bit iffy since I could see other cases besides running (perhaps Pending) where we would want to ensure the KafkaStreams::close it called.
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
logger.fatal("Caught Shutdown request");
// Do some shutdown cleanup.
if (streams.state().isRunning())
{
If this hook is called due to the Main exiting after handling
an exception we don't want to call close again. It doesn't
cause any errors but logs that the application was closed
a second time.
streams.close(100L, TimeUnit.MILLISECONDS);
}
// Maybe do a little bit more clean up before system exits.
System.exit(0);
}));
streams.setUncaughtExceptionHandler((t, e) -> {
logger.fatal("Caught unhandled Kafka Streams Exception:", e);
// Do some exception handling.
if (streams.state().isRunning())
{
streams.close(100L, TimeUnit.MILLISECONDS);
}
// Maybe do some more exception handling.
// Open the Gate to let application exit normally
shutdownLatch.countDown();
// Or Optionally call halt to immediately terminate and prevent call to Shutdown hook.
Runtime.getRuntime().halt(0);
});
Any suggestions about why calling the KafkaSteams:close in the exception handler would be causing such troubles or if there is a better way to implement shutdown hook and the exception handler at the same time it would be greatly appreciated?
Calling close() from an exception handler and from shutdown hook is slightly different. close() might deadlock if called from the shutdown hook (cf. https://issues.apache.org/jira/browse/KAFKA-4366) and thus, you should call it with a timeout.
Also, the issue is related with calling System.exit() from within an uncaught exception handler as described in the Jira. In general, calling System.exit() is quite harsh and should be avoided IMHO.
Your solution seems not to be 100% robust, either, because streams.state().isRunning() could result in a race condition.
An alternative to using a timeout might be to only set an AtomicBoolean within both the shutdown hook and the exception handler and use the "main()" thread to call close if the boolean flag is set to true:
private final static AtomicBoolean stopStreams = new AtomicBoolean(false);
public static void main(String[] args) {
// do stuff
KafkaStreams streams = ...
stream.setUncaughtExceptionHandler((t, e) -> {
stopStreams.set(true);
});
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
stopStreams.set(true);
});
while (!stopStreams.get()) {
Thread.sleep(1000);
}
streams.close();
}
"The default handler displays a string describing the exception, prints a
stack trace from the point at which the exception occurred, and terminates the program."
But this doesn't happen. Every time i intentionally create a DivideByZero exception but provide no exception handler, the default handler should have displayed a string with stack trace but my console is empty and program is not terminated only exception it shows is in debug panel. It may be small problem but every where i look the exception should have been printed in console but myconsole is empty.
I use eclipse neon.
Update from comment:
public class Example {
public static void main(String args[]){
System.out.println(10/0);
}
}
This should give ArithmeticException but there is nothing displayed at console.
If you Run the program, it will print stacktrace.
If you Debug the program, the debugger will (by default) halt execution when an uncaught exception is thrown, but it will (by default) not show the exception. Select Resume (F8) to continue execution, and the program will end and print stacktrace.
If you don't intend to debug the program, choose Run to start the program, not Debug.
If you want to debug, but don't want to halt execution on uncaught exception, open Window > Preferences, go to Java > Debug, and uncheck Suspend execution on uncaught exceptions.
If you still want to halt execution on uncaught exception, but you also want to actually see the exception, open Window > Preferences, go to Java > Debug, and check Open popup when suspended on exception. Source: Inspect current exception in Eclipse debugger?
Note: The above is from Eclipse Mars.2, not Neon, but should be the same.
I made many research on this subject without found a real answer.
Try to imagine a program which execute a multi thread calling a Callable.
For that, we launch an ExecutorService with a specific timeout which invoke all process.
So we have a try...catch block with multiple exception :
CancellationException for a timeout
ExecutionException if an exception is raised in the thread
InterruptedException for an abrupt stop...
Is the philosophy to log an message only, or to log the message and the throwable (so the stacktrace) ?
To sum up, should we do this :
} catch (CancellationException ce) {
logger.error("Timeout. Process cancelled", ce);
}
or just log the message error ?
Is stacktrace considered to appear only for bugs ?
Thank you.
For coding you should stick with the following pattern:
} catch (CancellationException ce) {
logger.error("Timeout. Process cancelled", ce);
}
The reason is that the Throwable captures the complete context of an error. If you omit parts of that context from the logger you'll never be able to access it later on if you need it. Even the Throwable class included with Java has been modified over time to include things like chained and suppressed exceptions. So even if you only want the message from this throwable you still might want to see the full stack traces for suppressed exceptions and exceptions causes.
On the output side, I think you can make that case that for some exceptions the stack trace is not important. In some cases the target audience must not or does not want to see exception stack traces. For these cases should leverage the features of the framework to change the published output to please the target audience. If the needs change over time you can tweak logging configuration without having to fix the application code.
Ive got the following ShutdownHook to detect when the application is exited:
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
// Do what you want when the application is stopping
sendMsg("", "goOfflineExit", "12");
}
}));
This works perfectly on Mac os but for some reason nothing gets fired on Windows.
Any ideas what im missing?
I can think of two possible explanations:
The sendMsg(...) call may be happening too late; e.g. after streams have been closed or flushed.
The sendMsg(...) call may be throwing an exception. Uncaught exceptions thrown in a shutdown hook typically don't get reported.
If you showed us the code of sendMsg we might be able to figure out a more definite answer.
After serving a few requests my eclipse has started breaking on processWorkerExit() method.
As per this link I know how to suppress the breaking of eclipse but is there any reason why the code is breaking on this line. Can there be a memory leak in such a case?
Tomcat 7.0.27
Eclipse 3.7.2
JDK 7.0.02
Answer is here: OpenJDK breaks on processWorkerExit with no breakpoint
In debug mode in eclipse by default, break on uncaught exceptions is
checked. Since you don't have a catch method here, it's likely that an
uncaught exception is being thrown and the debugger is breaking for
you immediately before the exception is thrown. You can turn it off in
preferences under Java->Debug.
The reason the debugger is stopping on that line is because there is an exception being thrown by the code within the try{} block, and that particular line of code is the next executable line of code after the exception is thrown. You can almost certainly see the stack trace of that exception in the console window, because by default an uncaught exception that bubbles up to Thread.run() will be sent to stderr.
As for your question about whether there can be a memory leak (or more likely, this being Java, a resource leak): the answer is yes, there could be. But there is nothing in that code to indicate that there is. If there were such a leak, it would almost certainly be because there is incorrect exception handling inside the task implementation.
I had this same problem. It breaks in your try/catch clause if you have one if you don't log the exception. Try inserting a breakpoint or output to LogCat like this :
try
{
//HERE I'VE PUT ALL THE FUNCTIONS THAT WORK FOR ME
Log.e("tag", "Sth passed!");
}
catch (Exception e)
{
//The task failed
Log.e("tag", e.getMessage());
}
If you don't have try/catch block put it like in above code. In LogCat you can see the last line of code that was run before exception it will help you to locate the error in your code just like this :
08-28 05:49:52.321: E/SQLiteDatabase(834): at java.lang.Thread.run(Thread.java:841)