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 isnotin 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 anyRuntimeExceptions 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 ownUncaughtExceptionHandler. Eric Burke has collectedsome 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 methodpublic void handle(Throwable aThrowable){...}
  • upon startup, add aSystemproperty 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值