异常

1.  程序执行过程中出现的影响程序正常运行的现象.
2.  异常语法
       try{
             //代码块
         }catch(异常类型 e){
         }catch(异常类型 2 e2){
         }...{
         }finally{
         }
     注意:try:表示可能出现异常的代码块.
           catch:抓取异常,并进行处理.
                  可以抓取多个异常.异常的范围要从小到大抓取.
                  并且只会执行第一个匹配的异常类型.
           finally:最终的,不管是否出现异常,finally中的代码块始终会执行
                    除虚拟机停止(System.exit(1))这种情况外.
              注意:finally 和 return的执行顺序:先执行return,把返回结果
                    保存在返回结果区域,并没有返回,再执行finally,最后,把
                    保存在结果区域的结果返回给调用者.

3.  throws声明异常
          a.就是当前方法,不能解决这个异常的时候,必须把这个异常交给上一个调用者去处理.
          b.语法
            访问修饰符 返回值类型 方法名(参数列表)[throws 异常]{}

package 二期第六章;

public class Test1 {

    public static void main(String[] args){

        try{
            sub();
        }catch(Exception e){
            System.out.println("---给你50块--");
        }catch(Throwable t){
            System.out.println("---给他一个酱油瓶---");
        }
    }
    public static int sub()throws Exception{
        System.out.println("---a--b--");
        return 0;
    }
View Code

 

package 二期第六章;

import java.util.InputMismatchException;
import java.util.Scanner;

public class TestEx {
    public static void main(String[] args){
        Scanner console = new Scanner(System.in);
        try{
            
            int a = console.nextInt();
            int b = console.nextInt();
        }catch(InputMismatchException ee){
            System.out.println("异常");
            ee.printStackTrace();
            String mes = ee.getMessage();
            System.out.println(mes);
        }catch(NullPointerException e){
            System.out.println("输入的不是整数");
        }catch(ClassCastException e1){
            System.out.println("---类型转换异常---");
        }finally{
            System.out.println("---最终的---");
        }
        System.out.println("运行结束");
    }
}
View Code

 

posted @ 2017-06-15 19:12  李李李i  阅读(119)  评论(0编辑  收藏  举报