Java4Android基础学习之异常

1、什么是异常

  1)中断了正常指令流的时间,(编译通过,但在运行的时候遇到了问题,无法继续进行)

2、异常的分类

  1)

异常有 编译时异常(Ecception) 和 运行时异常(RunTimeEcception)。

3、异常的处理

  1)使用 try catch finally,如:

public class test {
    public static void main(String arg []){
        try{
            int i = 1 / 0;//有可能产生错误的
        }
        catch (){//try 里面的代码出现异常则进入这里

        }
        finally {//不管try里的代码出不出错误都会进入这里
            
        }
    }
}

 4、自定义异常

  1)生成异常对象,然后抛出,如:

class test{
    int age;
    
    set_age(int age){
        if(age < 0){
               RunTimeException e = new RunTimeException(); //生成异常对象
               throw e; //抛出异常
         }
         this.age = age;
    }    
}

  2)throw 和throws

       throw为抛出异常,用法如上;throws为声明异常,如下:

class test{
    int age;
    
    set_age(int age) throws Exception{//声明异常,表示有可能产生异常
        if(age < 0){
              
         }
         this.age = age;
    }    
}

如果是声明异常,则需要在调用这个函数的地方使用try catch来处理,如:

class test{
        public static void main(String args []){
             age g = new age();
             try {//这个函数是声明了异常,这里调用他就必须捕捉处理
                 g.set_age(-10);
             }
             catch(Exception e){
                 System.out.println(e);//打印异常信息
             }  
        }
}
原文地址:https://www.cnblogs.com/YiStyle/p/5903086.html