Java-Exception(异常)

                           Throwable

Error(错误)                                    Exception (异常)
                                                   编译期                       运行时


Error:不可解决的致命错误!

Exception:可处理的异常!

 编译期异常:
        编译的时候就会出现异常。必须写try-catch,不然编译不通过

运行时异常:
       运行的时候才出现异常。写不写try-catch都可以

 

异常处理

为什么要处理?

 

1.出现的遗传信息只有程序员能够读懂,普通用户很难理解。

2.出现了异常程序不再执行,直接退出。

 

try......catch......finally

public class Test {
    public static void main(String args[]){
        int num1,num2;
        try{
           num1 = Integer.perseInt(args[0]);
           num2 = Integer.perseInt(args[1]);
        }catch(NumberFormatException e){
            System.out.println("请输入正确的数字!");
        }
         System.out.println(num1 + num2);
    }
}

 

 

常用的RunTimeException

NumberDormatException

ArrayIndexOutOfBoundsException 

NullPointerException空指针异常

普通的方法和属性必须有对象才能调用

当一个引用为NULL时,来调用了属性和方法就会发生此异常

catch可以捕获多个异常,但必须先捕获子类异常,再捕获父类异常。

 

thows关键字

用于将异常抛给调用它的环境

 

thow关键字

用来抛出自定义异常

 

 1 public class Files{
 2     public static void main(String args[]) throws Exception{
 3         Person p = new Person();
 4         p.setAge(131);
 5     }
 6 }
 7 
 8 class Person {
 9     private int age;
10     public void setAge(int age){
11         if(age<1 || age>130){
12             throw new AgeException("年龄必须在1-130岁之间,你输入的是:"+age);
13         }
14         this.age = age;
15     }
16     
17     public int getAge(){
18         return this.age;
19     }
20 }
21 
22 class AgeException extends RuntimeException {
23     public AgeException(String msg){
24         super(msg);
25     }
26 }

 

 

posted @ 2013-10-25 22:19  _Su  阅读(352)  评论(0)    收藏  举报