• 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)这样的构造器,这种构造器也不实用。你将看到,对异常来说

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

  • 相关阅读:
    SpringMVC(一)
    Mybatis二(高级部分)
    Mybatis一(基础)
    泛型
    itcast-Hibernate orm元数据和 关系操作
    自动装箱自动拆箱,基本数据类型
    struts2 中的数据访问servletAPI
    Hibernate 查询
    itcast-ssh-crm实践
    final修饰符(2)
  • 原文地址:https://www.cnblogs.com/fxyfirst/p/3800106.html
Copyright © 2020-2023  润新知