try {
this.interrupt();
} catch (IllegalThreadStateException e) {
e.printStackTrace();
}
I found out that an IllegalThreadStateException was thrown by putting print statement, no stack trace was printed. I have tried searching existing threads about Thread.interrupt() and IllegalThreadStateException, but didn't get much out of them. I am using CDLC 1.1, if it helps. thank you very much!!
CLDC 1.1 is supposed to support interrupt(), but CLDC 1.0 didn't. Maybe your particular implementation didn't feel like adding this support, and fakes it by throwing a runtime exception.
If no stack trace is printed, it sounds like there error is happening (and being handled) elsewhere. Can you step through the code in a debugger and see if that interrupt is triggering another thread to have a problem? It would have to occur with the process of executing interrupt().
In our IDE, I would put a breakpoint on that line, hit F5 to step inside the method call, then continue stepping inside until I found the problem. Along the way, if I get to a point where there is no source code I would download the related source jar file and point the debugger to it (which sounds involved but only takes about 2 minutes).
Hope that helps in some way,
-gMale
Related
I've come to the conclusion after reading from many sources that using printStackTrace for error handling is bad practice. Here's one.
Now I'm struck curious: in what cases is printing the stacktrace a valid solution? For the sake of the argument, let's assume we aren't working on a system such as a microwave or a banana, but a basic out-of-the-shelf PC.
The reason I'm asking this could be seen as a question in itself, but I'll tell you about it anyhoo:
I'm developing a snake-like game that can be played with AIs, and is intended for that purpose. All such AIs should extend an abstract class called SnakeLogic. All such AIs should also reside in their standalone .jar archives in a specific folder, from where the main program can find them and list them using classloaders.
The user can then choose one of his/her AIs from a list, should all stars fall in line, and play a game with this AI.
Now, I have a method in my main program that gets the next move from the AI like so:
public void startGame(int speed) {
gameInterface.showWindow();
Runnable moveCmd = () -> {
try {
for (Player player : snakeGame.getPlayers()) {
if (player.isDead()) {
continue;
}
String move = player.getLogicHandler().getMove();
Direction direction = Direction.directionFromString(move);
snakeGame.makeMove(player, direction);
}
gameInterface.getFrame().repaint();
snakeGame.wait(speed);
if (snakeGame.gameOver()) {
stopGame();
}
} catch (Exception ex) {
ex.printStackTrace();
stopGame();
}
};
/* moveSchedule is an instance of ScheduledExecutorService */
moveSchedule.scheduleAtFixedRate(moveCmd, 1000, speed, TimeUnit.MILLISECONDS);
}
I'm not going to get too involved with the code above. I'd like to draw your attention to the try-catch statement, however. As you can see I print the stacktrace and end the game, should an exception occur somewhere during the execution of the moveCmd runnable. This is the source of my curiosity: If I don't print the stacktrace like this, or if I remove the try-catch entirely, I never get any errors in the case of a runtime exception during the execution of that block. Why? Is it because it's wrapped inside the runnable? Note also that the line snakeGame.makeMove(player, direction); doesn't call any code in the main program; snakeGame is an instance of a SnakeLogic, which resides in an external .jar.
Why don't I get any errors if I remove the try-catch? Also, in this case, is printing the stacktrace a good idea?
I understand this imposes two questions for you: the topic and the above. I want to emphasize the topic, so don't get too sidetracked with the second question; though insight is duly noted, there's nothing broken in my code.
You need to shift your thought process a bit when dealing with error and exceptions. It is always a good practice to print the error trace. Now the question is where to print. by default printStackTrace prints to your standard console. of course you can redirect that output to a log file like Tomcat does but that is a work around, if you ask me.
In production and pre-prod systems and even in distributable spftware where you distribute a desktop application to users for running on PCs you may or may not have dedicated access to console. Further more what prints on console is lost once the console is closed or app finishes. You need to persist the errors somewhere for analysis later. Normally folks design the app to zip and send error logs periodically to developers for analysis.
Now if you think about the whole scenarios the bottom line is to preserve the errors somewhere for analysis later. So usually do it in a rotating log file or in DB. Console wont suffice. Thus incidentally the catch block should have a log statement to log the exception.
The problem with Exception.printStackTrace() is that it writes to your console (most probably) which is a synchronous operation. Not to mention that writing to console is slow in most platforms. You dont want to hold off your execution thread until the full stack trace is written. So its better to hand it over to a log framework like log4j which has the ability to write the complete stack trace into to file asynchronously (other appenders are available), so that the execution thread returns immediately to the callee and yet the log contains necessary details.
So its a question of synchronous write or asynchronous write. As Nazgul pointed out, you have to log exceptions in a system for later analysis where ever applicable.
NotE: A problem with asynchronous logging is that if the process dies abruptly, like in kill -9 or system powered down, you may loose the buffered content before OS has chance to write it to disk
I have try/catch blocks at lower levels to handle most errors, but I was told we need one near the top, basically as a catch all to allow the program to continue operating correctly if there is an error. I put a try/catch(Exception e)/finally around everything at the top level, but we are still getting exceptions causing crashes. I've been looking at the stack trace for any clues... It starts like this (I can post more of it if that would help):
111858 [SimpleAsyncTaskExecutor-2] DEBUG o.h.e.jdbc.spi.SqlExceptionHelper - could not execute statement [n/a]
java.sql.SQLIntegrityConstraintViolationException: ORA-01400: cannot insert NULL into ("DATABASE"."TABLE"."COLUMN")
The weird thing is that the rest of the stack trace never goes back to anything that is ours. It's all oracle/apache/hibernate/springframework until it ends up with:
at java.lang.Thread.run(Thread.java:795) [na:1.7.0]
Any ideas why it's not going back to our code or how better to implement this "catch all"? The finally block is for some steps that we want to implement whether there is an error or not.
Edit: for clarity's sake and because maybe it will help, this is part of a batch that processes files every 5 minutes. The try/catch is like so:
try{
//process file
}catch(Exception e){
//log exception
}finally{
//mark file as processed so it doesn't keep trying to reprocess a broken file
}
You, or a library that you are using must be spawning off a thread somewhere and it is that thread that is throwing the exception.
Your options are
track down the creation of that thread, and handle the exception from there
track down which thread group that the thread belongs to and register an exception handler with that thread group
The best idea I can suggest for implementing this "catch all" is don't do it.
I would, instead, recommend defensive programming at the class level. Each class should handle its own possible exceptions when possible. This will save you time later when something goes wrong and you have to track down where to came from.
You need to debug and find where the thread is being created and handle exceptions there.
I've done some research to know if there is an equivalent to PHP die in java
Sometimes I'm doing small tests and I really want to stop my code at specific line , and return doesnt stop the code like "die" in php
Is there a die quivalent in java?
Use System.exit(0); to exit the java code.
Keep a note this will stop the JVM instance which is currently running.
If you want to come out of a method use return or throw exception to showcase error condition.
try:
System.out.println(message);
System.exit(0);
Disclaimer: I'm not that familiar with Java, I have a basic working knowledge of it, but haven't done a huge amount of work with it.
I suppose you could just throw() an exception and not catch it, that should halt execution. Of course if you have an exception handler for exceptions that aren't caught locally you might have problems.
Most IDEs let you set breakpoints where execution will stop and you'll be able to examine the state of variables, look at the call stack and so on. Both Eclipse and Netbeans support this. It might be a better option.
EDIT: There is also System.exit() which will halt execution. I still think breakpoints are a better option though.
<% if(true)return; %> ok
My project generates some text/binary files. If I run it normally, some files will have a pretty low size ( which indicates something went wrong ). If I run it from debug mode ( stepping through code ), the files will be generated correctly.
What can cause this behaviour? I'm pretty sure I don't have any unclosed files.
EDIT: I've gone through the code in a more focused way, and I've found the problem. At one point in time, the files get compressed, and this explains the decrease in size. I'm stupid :)
A moderator can close this question if he sees fit.
Try adding:
System.gc();
try { Thread.sleep(4000); } catch (Exception e) {}
System.gc();
...at the end of your program. If the problem goes away then you did forget to close() a file. The above code is no solution, it is a hacky attempt to increase the likelyhood finalizers will run.
Is your code multithreaded? Are you trying to read something that you haven't given another thread a chance to finish constructing, which doesn't manifest when you're stepping through it?
Do you call some kind of "read" method, to read from a file, for example, and assume that you will always get back the number of bytes that you request?
When running our program we get an exception of type java.lang.IllegalMonitorStateException. On Java6 API website, it says there is a constructor that gives a details about the exception: IllegalMonitorStateException(String s)
How can we use this to get a better idea of where the bug is in our code? Is there anything else we can do (besides lots of debugging which we're currently doing) to pinpoint the function or line that failed?
The details must be given when the Exception is created (Constructor, right?) and if you are not creating it, there is no way for you to provide the details.
You can analize the StackTrace of the Exception. It shows the classes, methods and souce line which were called to cause the Exception.
One cause for the IllegalMonitorStateException is trying to wait on an Object without having synchronized on it. See the Javadoc.
There are other possible causes and the Exception may be thrown by some library/external code. I think only the StackTrace can help...
This is maybe occurring because the instance of the object which you are calling wait or notify on is different that the instance you synchronized with. For example:
Integer a;
a = new Integer(0);
synchronized(a) {
System.out.printf("I synchronized on %h.", a);
++a;
System.out.printf("But, I am calling notify for %h and I hold no lock for it.", a);
a.notify();
}
This will throw the IllegalMonitorStateException because the instance that 'a' points to is no longer the same.
How can we use this to get a better
idea of where the bug is in our code?
Is there anything else we can do
(besides lots of debugging which we're
currently doing) to pinpoint the
function or line that failed?
In this case, printing the message by itself probably won't help much. What you need is a stacktrace with source file names and line numbers.
Make sure that all relevant ".class" files / JARs were built with file and line number debug information included. This is the default, but compiling with "-g:none" will strip this ... as will most JAR file obfuscators.
Next, add a try / catch block to catch the IllegalMonitorStateException and either call ex.printStackTrace() or log the exception.
From the stacktrace you should be able to see what line in the code threw the exception. The chances are that is was a call to Object.wait(...) or something like that. Check the javadoc for the offending method to find out what circumstances cause the exception to be thrown.
(And once you are done, remember to move the try / catch block you added.)
You should print the stack trace, which will give you the exact location in the source.
Unfortunately it's not uncommon for the JVM to throw exceptions which contain no detail message to assist in debugging.