views:

71

answers:

3

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?

A: 

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.

Software Monkey
+1  A: 

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

Carlos Heuberger
A: 

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.

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

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

Stephen C