20

プロジェクトで通常の例外を処理するためにMyExceptionHandler実装するというクラスを使用しています。Thread.UncaughtExceptionHandler

私が理解しているように、このクラスは EDT 例外をキャッチできないため、main()メソッドでこれを使用して EDT 例外を処理しようとしました。

public static void main( final String[] args ) {
    Thread.setDefaultUncaughtExceptionHandler( new MyExceptionHandler() );  // Handle normal exceptions
    System.setProperty( "sun.awt.exception.handler",MyExceptionHandler.class.getName());  // Handle EDT exceptions
    SwingUtilities.invokeLater(new Runnable() {  // Execute some code in the EDT. 
        public void run() {
            JFrame myFrame = new JFrame();
             myFrame.setVisible( true );
        }
    });
}

しかし、今までうまくいきませんでした。たとえば、JFrame の初期化中に、次のようにコンストラクターのバンドル ファイルからラベルをロードします。

setTitle( bundle.getString( "MyJFrame.title" ) );

例外ハンドラをテストするためにバンドル ファイルからキーを削除しましたMyJFrame.titleが、機能しませんでした。例外は通常、ログに出力されました。

ここで何か間違ったことをしていますか?

4

3 に答える 3

31

EDT 例外ハンドラは を使用しませんThread.UncaughtExceptionHandler。代わりに、次のシグネチャを持つメソッドを呼び出します。

public void handle(Throwable thrown);

それを に追加するとMyExceptionHandler、動作するはずです。

これに関する「ドキュメント」EventDispatchThreadは、 のパッケージ プライベート クラスである にありjava.awtます。そこでのjavadocからの引用handleException()

/**
 * Handles an exception thrown in the event-dispatch thread.
 *
 * <p> If the system property "sun.awt.exception.handler" is defined, then
 * when this method is invoked it will attempt to do the following:
 *
 * <ol>
 * <li> Load the class named by the value of that property, using the
 *      current thread's context class loader,
 * <li> Instantiate that class using its zero-argument constructor,
 * <li> Find the resulting handler object's <tt>public void handle</tt>
 *      method, which should take a single argument of type
 *      <tt>Throwable</tt>, and
 * <li> Invoke the handler's <tt>handle</tt> method, passing it the
 *      <tt>thrown</tt> argument that was passed to this method.
 * </ol>
 *
 * If any of the first three steps fail then this method will return
 * <tt>false</tt> and all following invocations of this method will return
 * <tt>false</tt> immediately.  An exception thrown by the handler object's
 * <tt>handle</tt> will be caught, and will cause this method to return
 * <tt>false</tt>.  If the handler's <tt>handle</tt> method is successfully
 * invoked, then this method will return <tt>true</tt>.  This method will
 * never throw any sort of exception.
 *
 * <p> <i>Note:</i> This method is a temporary hack to work around the
 * absence of a real API that provides the ability to replace the
 * event-dispatch thread.  The magic "sun.awt.exception.handler" property
 * <i>will be removed</i> in a future release.
 */

サンがあなたがこれを見つけることをどれほど正確に期待していたか、私にはわかりません。

EDT のオンとオフの両方で例外をキャッチする完全な例を次に示します。

import javax.swing.SwingUtilities;

public class Test {
  public static class ExceptionHandler
                                   implements Thread.UncaughtExceptionHandler {

    public void handle(Throwable thrown) {
      // for EDT exceptions
      handleException(Thread.currentThread().getName(), thrown);
    }

    public void uncaughtException(Thread thread, Throwable thrown) {
      // for other uncaught exceptions
      handleException(thread.getName(), thrown);
    }

    protected void handleException(String tname, Throwable thrown) {
      System.err.println("Exception on " + tname);
      thrown.printStackTrace();
    }
  }

  public static void main(String[] args) {
    Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());
    System.setProperty("sun.awt.exception.handler",
                       ExceptionHandler.class.getName());

    // cause an exception on the EDT
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        ((Object) null).toString();        
      }
    });

    // cause an exception off the EDT
    ((Object) null).toString();
  }
}

それはそれを行う必要があります。

于 2010-12-15T09:47:52.353 に答える
0

追加情報として、多くの場合、Throwable は 1.5 および 1.6 でも EDT の UncaughtExceptionHandler によってキャッチされる可能性があります。1.5.0_22 の EventDispatchThread のソース コードを見ると、次のようになります。

private void processException(Throwable e, boolean isModal) {
    if (!handleException(e)) {
        // See bug ID 4499199.
        // If we are in a modal dialog, we cannot throw
        // an exception for the ThreadGroup to handle (as added
        // in RFE 4063022).  If we did, the message pump of
        // the modal dialog would be interrupted.
        // We instead choose to handle the exception ourselves.
        // It may be useful to add either a runtime flag or API
        // later if someone would like to instead dispose the
        // dialog and allow the thread group to handle it.
        if (isModal) {
            System.err.println(
                "Exception occurred during event dispatching:");
            e.printStackTrace();
        } else if (e instanceof RuntimeException) {
            throw (RuntimeException)e;
        } else if (e instanceof Error) {
            throw (Error)e;
        }
    }
}

private boolean handleException(Throwable thrown) {

    try {

        if (handlerClassName == NO_HANDLER) {
            return false;   /* Already tried, and failed */
        }

        /* Look up the class name */
        if (handlerClassName == null) {
            handlerClassName = ((String) AccessController.doPrivileged(
                new GetPropertyAction(handlerPropName)));
            if (handlerClassName == null) {
                handlerClassName = NO_HANDLER; /* Do not try this again */
                return false;
            }
        }

        /* Load the class, instantiate it, and find its handle method */
        Method m;
        Object h;
        try {
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            Class c = Class.forName(handlerClassName, true, cl);
            m = c.getMethod("handle", new Class[] { Throwable.class });
            h = c.newInstance();
        } catch (Throwable x) {
            handlerClassName = NO_HANDLER; /* Do not try this again */
            return false;
        }

        /* Finally, invoke the handler */
        m.invoke(h, new Object[] { thrown });

    } catch (Throwable x) {
        return false;
    }

    return true;
}

このコードによると、Throwable が EDT スレッドの UncaughtExceptionHandler によってキャッチされない方法は 3 つしかありません。

  1. Throwable は、sun.awt.exception.handler によって正常に処理されます (クラスが検出され、インスタンス化され、何もスローせずにその handle(Throwable) メソッドが呼び出されます)。
  2. EDT はモーダル ダイアログにあります
  3. Throwable は RuntimeException でも Error でもありません
于 2014-02-03T19:33:03.247 に答える