Provide an uncaught exception handler

In Java programs, what happens when an uncaught RuntimeException is thrown, but is not handled by your program? In the simplest Java programs run from the console and executed in a single thread, the default behavior is to :
  • print a stack trace to the console
  • terminate the thread (and thus terminate the program itself)

There are two common kinds of programs where the above behavior is not in effect:

  • programs running in a servlet container
  • Swing applications

In Swing applications, the default behavior still prints the stack trace to the console, but the Event Dispatch Thread (the main Swing thread) is not terminated. The Event Dispatch Thread always remains alive, in spite of any RuntimeExceptions thrown by your program.

However, simply printing a stack trace to the console in a Swing application is not very informative for the average end user. Instead, you should likely override Java's default handling of uncaught exceptions. The benefits are:

  • the end user is kept informed of problems more effectively
  • new behavior can be added, such as logging or sending emails to support staff

If you are using JDK 5+, then you may define your own UncaughtExceptionHandler. Eric Burke has collected some good advicefor implementing such a handler.

In JDK 1.4, the simplest way of overriding the default handler for uncaught exceptions is to use the following undocumented feature:

  • create a class with a no-argument constructor
  • add to it a method public void handle(Throwable aThrowable){...}
  • upon startup, add a System property named 'sun.awt.exception.handler', whose value is the fully qualified class name of this new handler class

Example 

package hirondelle.movies.exception;

import hirondelle.movies.util.Util;
import hirondelle.movies.util.ui.UiUtil;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 Custom handler for uncaught exceptions.
 
 <P>By default, a Swing app will handle uncaught exceptions simply by 
  printing a stack trace to {@link System#err}. However, the end user sees 
  nothing happen. This class addresses that problem, by showing the end user a 
  simple error message in a modal dialog. (The dialog's owner is the 
  currently active frame.)
  
 <P>In JDK1.4, the simplest way of overriding the default handler for uncaught 
 exceptions is to use the following undocumented feature :
 <ul>
   <li>create a class with a no-argument constructor
   <li>add to it a method :<tt>public void handle(Throwable aThrowable){...}</tt>
   <li>upon startup, add a {@link System} property named 
   <tt>'sun.awt.exception.handler'</tt>, 
   whose value is the fully qualified class name of this new handler class
   </ul> 
 
 The above technique is used by this class. 
 
 <P>Other alternative methods include :
 <ul>
   <li>create a custom {@link java.util.logging.Handler}, and attach it to your 
    application's loggers
   <li>override 
   {@link ThreadGroup#uncaughtException(java.lang.Thread, java.lang.Throwable)}
   <li>use later versions of Java, which provides an API related to this problem
  </ul> 
*/
public final class ExceptionHandler {

  /**
   No-argument constructor.
  This class must have a no-arg constructor (see class comment).
  */
  public ExceptionHandler(){
    //empty
  }
  
  /** 
   Custom handler for uncaught exceptions.
   
   <P>Displays a simple model dialog to the user, showing that an error has occured.  
   The text of the error includes {@link Throwable#toString()}.
  */
  public void handle(Throwable aThrowable){
    fLogger.severe(getStackTrace(aThrowable));
    JOptionPane.showMessageDialog(
      UiUtil.getActiveFrame(), "Error: " + aThrowable.toString(), 
      "Error", JOptionPane.ERROR_MESSAGE
    );
  }

  // PRIVATE //
  private static final Logger fLogger = Util.getLogger(ExceptionHandler.class);
  
  private String getStackTrace(Throwable aThrowable) {
    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);
    aThrowable.printStackTrace(printWriter);
    return result.toString();
  }
}


http://www.javapractices.com/topic/TopicAction.do?Id=229
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读