java 入门测试代码(五)

异常的结构图。

自定义异常类:

    static void test8()
    {
        // 自定义异常类
        class ServerTimedOutException extends Exception
        {
            //创建成员变量
            private String resion;
            private int port;

            //创建构造函数
            public ServerTimedOutException(String resion, int port)
            {
                this.resion = resion;
                this.port = port;
            }

            public String getReason() {
                return resion;
            }
        }


        // 这里是捕获这个异常的情况
        try
        {
            int a = 100;
            a = a / 0;

            //抛出异常对象
            throw new ServerTimedOutException( "this is resion(8888)...", 80 );
        }
        // 捕获我们定义的异常
        catch(ServerTimedOutException e)
        {
            //处理异常
            System.out.println( e.getReason() );
        }
        // 捕获所有异常
        catch( Exception e ){
            System.out.println( e.toString() );
        }
        
    }

猜你喜欢

转载自blog.csdn.net/yangzm/article/details/87862807