简体   繁体   English

为什么我的Java异常在SwingWorker中抛出时不会打印堆栈跟踪?

[英]Why doesn't my Java exception print a stack trace when thrown inside a SwingWorker?

Why is it that when I wrap a SwingWorker around this code it no longer reports an exception being thrown? 为什么当我围绕此代码包装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;
    }
}

You have to call get() to retrieve any exceptions that occurred in doInBackground() . 您必须调用get()来检索doInBackground()中发生的任何异常。 For example, you can do it in done() method, ie: 例如,您可以在done()方法中执行此done() ,即:

@Override
protected void done() {
    try {
        get();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM