zoukankan      html  css  js  c++  java
  • Java 异常(自定义异常)

      Java提供的异常体系不可能预见所有的希望加以报告的错误,所以可以自己定义异常类来表示程序中可能会遇到的特定问题。

         要自己定义异常类,必须从已有的异常类集成,最好的选择意思相近的异常类继承,建立新的异常类型最简单的方法就是让编译器舞步产生默认的构造器,

    所以这几乎不用写多少代码:

     4 package com.exceptions;
    10 class SimpleException extends Exception{}
    11 
    12 public class InheritingExceptions {
    13 
    14     /**
    15      * 
    16      */
    17     public InheritingExceptions() {
    18         // TODO Auto-generated constructor stub
    19     }
    20     public void f() throws SimpleException{
    21         System.out.println("Throw SimpleException from f()");
    22         throw new SimpleException();
    23     }
    24     
    25     /**
    26      * @param args
    27      */
    28     public static void main(String[] args) {
    29         // TODO Auto-generated method stub
    30         InheritingExceptions sed = new InheritingExceptions();
    31         try{
    32             sed.f();
    33         }catch(SimpleException e){
    34             System.out.println("Caught it");
    35             
    36             
    37         }
    38     }
    39 
    40 }
    结果:
    1 Throw SimpleException from f()
    2 Caught it

     编译器创建了默认的构造器,它将自动调用基类的默认构造器。本例中不会得到想SimpleException(String)这样的构造器,这种构造器也不实用。你将看到,对异常来说

    最重要的就是类名,所以本例中建立的异常类在大多数情况下已经够用。

  • 相关阅读:
    Java 1.7.0_21b11 Code Execution
    nginx NULLByte 任意代码执行漏洞
    nginx ‘ngx_http_close_connection()’远程整数溢出漏洞
    WordPress WP Super Cache插件任意代码执行漏洞
    memcached 远程拒绝服务漏洞
    原环套原环
    要去哈尔滨了
    母亲节就要到了,你忘了吗?
    对于流媒体服务的一点概念
    有了螃蟹让心情好一点
  • 原文地址:https://www.cnblogs.com/fxyfirst/p/3800106.html
Copyright © 2011-2022 走看看