背景
当异常不在调试的机器上发生的时候,我们可能需要记录异常并且发送给远端服务器。
场景
创建一个移动应用,当用户的某些操作,或者是特定手机上运行出现异常的时候,我们可能需要将异常发送给开发者。
实例
Reporter.java
public interface Reporter {
    public void report(Throwable t);
}
ExceptionReporter.java
public class ExceptionReporter {
    public static final Reporter PrintException = new Reporter() {
        @Override
        public void report(Throwable t) {
            System.out.println(t.toString());
        }
    };
    private static Reporter defalutReporter = PrintException;
    public static Reporter getPrintException(){
        return PrintException;
    }
    public static Reporter getExceptionReporter(){
        return defalutReporter;
    }
    public static Reporter setExceptionReporter(Reporter reporter){
        defalutReporter = reporter;
        return defalutReporter;
    }
}
EmailExceptionReporter.java
public class EmailExceptionReporter implements Reporter {
    @Override
    public void report(Throwable t) {
        sendMessage(t.toString());
    }
    private void sendMessage(String message){
        // Send email
    }
}
Test.java
public class Test {
    public static void main(String args[]){
        try{
            int a[] = {0, 0};
            System.out.print(a[2]);
        }catch (Exception e){
            ExceptionReporter.getPrintException().report(e);
        }
        try{
            String b = null;
            b.toCharArray();
        }catch (Exception e){
            ExceptionReporter.setExceptionReporter(new EmailExceptionReporter()).report(e);
        }
    }
}
原文:http://my.oschina.net/sulliy/blog/488304