is it possible to obtain somehow source string from NumberFormatException in catch clause eg.:
try {
Integer.parseInt("test");
} catch (NumberFormatException e) {
e.sourceString(); \\ to return "test"
}
Thanks. Stefan
There is no good way to do what you ask; better to save the variable before the try
block.
Here's the source code that creates the exception:
static NumberFormatException forInputString(String s) {
return new NumberFormatException("For input string: \"" + s + "\"");
}
As you can see, the parse string is not stored in the exception, as it creates the error message as part of the constructor. However, because we always know the format, we could write something like this:
try {
int foo = Integer.parseInt("foo");
} catch (NumberFormatException e) {
String message = e.getMessage();
System.out.println(message.substring(19, message.length() - 1));
}
Therefore, as @chrylis said, storing the value in a variable before the try
block and using it if there's an exception is the best solution.
Two reasons not to do it this way (which is really the only way to do what you've asked in the OP):
String