码迷,mamicode.com
首页 > 编程语言 > 详细

Java-- 异常(自定义异常)

时间:2014-06-22 23:42:02      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   java   ext   

  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-- 异常(自定义异常),布布扣,bubuko.com

Java-- 异常(自定义异常)

标签:style   class   blog   code   java   ext   

原文地址:http://www.cnblogs.com/fxyfirst/p/3800106.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!