【发布时间】:2013-02-04 20:39:17
【问题描述】:
为什么当我将 SwingWorker 包裹在这段代码周围时,它不再报告抛出异常?
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;
}
}
【问题讨论】:
-
它没有按照您的预期抛出或报告吗?
-
没有被报告。我假设它被抛出但堆栈跟踪没有打印。
-
我的猜测是仍然会抛出异常,但是内部处理程序对
doInBackground()的调用被包装在一个旨在忽略异常的 try-catch 语句中。