Beware of unknown root causes

http://www.javapractices.com/topic/TopicAction.do?Id=235


All exceptions are based on the Throwable class. By default, all Throwables can have an underlying root cause. The root cause may be set in the Throwable's constructor, or after construction by calling initCause.

Having the root cause is very useful for troubleshooting. However, there is a case in which root causes can cause a problem. When a Throwableis passed over the network, it must first be serialized, and then reconstructed (deserialized) on the other end. If the root cause inside aThrowable object is not known to the receiver on the other end, then what happens? The receiver will throw a NoClassDefFoundError. Of course, this replaces the original exception with something unrelated.

One option is to define a "locked down" exception, which can hold only null as the root cause.

Example

This class is a checked exception which cannot take a root cause. 

/**
  A checked exception that cannot be given a root cause.
  
  All calls to {@link #getCause()} will return <tt>null</tt>.
  This class cannot be subclassed. 
*/
public final class LockedDownException extends Exception {
  
  /**
   The sole constructor.
   No root cause can be passed to this constructor.
  */
  public LockedDownException(String aMessage){
    super(aMessage);
  }
  
  /**
   Always coerces the root cause to <tt>null</tt>.
    
   <P>Even though the caller is allowed to call this method, it will never
   have any effect. The caller is not allowed to set the root cause, neither
   during construction, nor after construction.
  */
  @Override public synchronized Throwable initCause(Throwable aRootCause) {
    return super.initCause(null);
  }
  

  /** Simple test harness. */
  public static void main(String... aArgs){
    LockedDownException ex = new LockedDownException("Hello");
    ex.initCause(new IllegalArgumentException("Test"));
    System.out.println(ex.getCause()); //prints 'null'
  }
} 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值