Why is it that when I wrap a SwingWorker around this code it no longer reports an exception being thrown?
import java.security.InvalidParameterException;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
IntegerString s = new IntegerString("EIGHT");
return null;
}
}.execute();
}
});
}
}
class IntegerString {
public IntegerString(String s) {
if (!isInteger(s)) {
System.out.println("...throwing exception.");
throw new InvalidParameterException("Thrown.");
}
// ...
}
static boolean isInteger(String str) {
if (str == null) {
return false;
}
int length = str.length();
if (length == 0) {
return false;
}
int i = 0;
if (str.charAt(0) == '-') {
if (length == 1) {
return false;
}
i = 1;
}
for (; i < length; i++) {
char c = str.charAt(i);
if (c <= '/' || c >= ':') {
return false;
}
}
return true;
}
}
Using printStackTrace() method − It print the name of the exception, description and complete stack trace including the line where exception occurred. Using toString() method − It prints the name and description of the exception. Using getMessage() method − Mostly used. It prints the description of the exception.
A trace of the method calls is called a stack trace. The stack trace listing provides a way to follow the call stack to the line number in the method where the exception occurs. The StackTrace property returns the frames of the call stack that originate at the location where the exception was thrown.
You can obtain a stack trace from a thread – by calling the getStackTrace method on that Thread instance. This invocation returns an array of StackTraceElement, from which details about stack frames of the thread can be extracted.
Logging the stack traces of runtime exceptions assists developers in diagnosing runtime failures. However, unnecessary logging of exception stack traces can have many negative impacts such as polluting log files.
You have to call get()
to retrieve any exceptions that occurred in doInBackground()
. For example, you can do it in done()
method, ie:
@Override
protected void done() {
try {
get();
} catch (Exception e) {
e.printStackTrace();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With