I want to be able to identify an exception at a running Java code without attaching a debugger. For a simple example, if I have the following code:
int i = 0;
Random rand = new Random();
while (true)
{
i++;
int number = rand.nextInt(1000);
if (number =开发者_JS百科= 20)
throw new Exception("Error!!!");
}
How can I know the value of "i" at the time of the exception throw? (without attaching any debuggers or adding log/print entries).
My motivation is that I want to be able to identify a problem at a customer site without attaching any debuggers to the production site.
If Someone was asking the same question using .Net or C++ I could get the value of "i" using Windbg and the relevant PDBs
Thanks!
Add the relevant information to the Exception
object.
if (number == 20)
throw new Exception("Error!!! i = " + i);
You can retrieve the value of i
in the catch
block, using Exception.getMessage()
(and some string parsing, in this case; alternatively, just throw new Exception("" + i)
).
Your question is unclear.
If you are actually asking how you can find out information about the execution state of a program without either attaching a debugger or modifying the program to add logging / tracing / whatever that will give you that information .... then the answer is "You can't do it".
In that situation, your only option is to attempt to reason about the program's behaviour.
In your example, the random number generator returns numbers that are (for all practical purposes) unpredictable, and therefore not amenable to reasoning. And that would normally be the end of it.
However, @Thomas Jungblut's comment points out that this is irrelevant, and the answer is ZERO ... because nothing in your program changes the value of i
after it has been initialized.
But this really doesn't alter the "general" answer:
- If you can't trace it / debug it, you have to reason about it.
- If you can't reason about it, you are stuck.
精彩评论