Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 449|回复: 0

[Java基础知识]异常回调

[复制链接]
  • TA的每日心情
    开心
    2021-3-12 23:18
  • 签到天数: 2 天

    [LV.1]初来乍到

    发表于 2014-10-1 00:48:33 | 显示全部楼层 |阅读模式
    java程序发生异常时,我们一般用try,catch块来处理,但我们也可以实现自己的异常回调机制把发生的异常(包括RuntimeException)通知到我们处理异常的对象。

         首先定义我们自己的处理异常的类(异常临听器),它实现ExceptionListener接口。

    public interface ExceptionListener {
    public void exceptionOccurred(Exception x, Object source);
    }

         第一个参数是发生的异常的引用,第二个参数是捕获该异常的类的引用。

    如下是一个实现类:  
      
       
       
         
       
                        
         
       
      

    public class ExceptionCallbackMain extends Object implements ExceptionListener {

            private int exceptionCount;
            public ExceptionCallbackMain() {
                    exceptionCount = 0;
            }
            public void exceptionOccurred(Exception x, Object source) {
               exceptionCount++;
               System.err.println("EXCEPTION #" + exceptionCount +", source=" + source);
               x.printStackTrace();
            }
            public static void main(String[] args) {
               ExceptionListener xListener = new ExceptionCallbackMain();
               ExceptionCallback ec = new ExceptionCallback(xListener);
            }
    }

           xListener对象将监视ec对象,一旦活动的ec对象内部发生异常,将触发exceptionOccurred(x,source)的调用来处理异常。请看ExceptionCallback.java源文件:
    import java.io.*;
    import java.util.*;

    public class ExceptionCallback extends Object {
             private Set exceptionListeners;//多个临听器的集合
             private Thread internalThread;//内部线程,自运行对象,用来产生异常
             private volatile boolean noStopRequested;

             public ExceptionCallback(ExceptionListener[] initialGroup) {//构造函数
                     init(initialGroup);//有一组临听器
             }

             public ExceptionCallback(ExceptionListener initialListener) {//构造函数,添加一个临听器
                     ExceptionListener[] group = new ExceptionListener[1];
                     group[0] = initialListener;
                     init(group);
             }

             public ExceptionCallback() {
                     init(null);
             }

    private void init(ExceptionListener[] initialGroup) {
                     System.out.println("in constructor - initializing...");
                     exceptionListeners =Collections.synchronizedSet(new HashSet());
                     if ( initialGroup != null ) {
                           for ( int i = 0; i < initialGroup.length; i++ ) {
                               addExceptionListener(initialGroup);
                           }
                      }

                     noStopRequested = true;
                     Runnable r = new Runnable() {
                                 public void run() {
                                                 try {
                                                     runWork();//产生异常的代码
                                                 } catch ( Exception x ) {
                                                  sendException(x);//传速异常
                                                }
                                 }};
                     internalThread = new Thread(r);//内部线程
                     internalThread.start();
             }

             private void runWork() {
                    try {
                            makeConnection(); // will throw an IOException
                    } catch ( IOException x ) {
                            sendException(x);//传速异常
                    }  
                    String str = null;
                    int len = determineLength(str); // NullPointerException
            }

            private void makeConnection() throws IOException {
                     String portStr = "j20";  
                     int port = 0;
                     try {
                         port = Integer.parseInt(portStr);//产生一个异常
                     } catch ( NumberFormatException x ) {
                               sendException(x);//传速异常
                               port = 80;  
                     }  
                     connectToPort(port); // will throw an IOException
            }

            private void connectToPort(int portNum) throws IOException {
                     throw new IOException("connection refused");
            }

            private int determineLength(String s) {
                     return s.length();
            }

            public void stopRequest() {
                     noStopRequested = false;
                     internalThread.interrupt();
            }

            public boolean isAlive() {
                     return internalThread.isAlive();
            }

            private void sendException(Exception x) {
                     if ( exceptionListeners.size() == 0 ) {//如果没有临听器
                             x.printStackTrace();
                             return;
            }


                      synchronized ( exceptionListeners ) {
                            Iterator iter = exceptionListeners.iterator();
                            while ( iter.hasNext() ) {
                            ExceptionListener l =(ExceptionListener) iter.next();
                            l.exceptionOccurred(x, this);//处理异常
                            }
                     }
           }

           public void addExceptionListener(ExceptionListener l) {//添加一个临听器
                            if ( l != null ) {
                                 exceptionListeners.add(l);
                            }
           }

           public void removeExceptionListener(ExceptionListener l) {//删除一个临听器
                            exceptionListeners.remove(l);
           }

           public String toString() {
                           return getClass().getName() +"[isAlive()=" + isAlive() + "]";
           }
    }

      

      
      
       
       

         
       

         
       
      



      



                            function TempSave(ElementID)
                            {
                                    CommentsPersistDiv.setAttribute("CommentContent",document.getElementById(ElementID).value);
                                    CommentsPersistDiv.save("CommentXMLStore");
                            }
                            function Restore(ElementID)
                            {
                                    CommentsPersistDiv.load("CommentXMLStore");
                                    document.getElementById(ElementID).value=CommentsPersistDiv.getAttribute("CommentContent");
                            }
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-5-10 10:26 , Processed in 0.386406 second(s), 46 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表