Java基础知识强化之IO流笔记04:throw和throws的区别

1. throw概述

在功能方法内部出现某种问题,程序不能继续运行,需要进行跳转时,就用throw把异常对象抛出。

 

2. 案例演示:

(1)

 1 package com.himi.throwdemo;
 2 
 3 public class ExceptionDemo2 {
 4     public static void main(String[] args) {
 5          method();
 6         
 7 //        try {
 8 //            method2();
 9 //        } catch (Exception e) {
10 //            e.printStackTrace();
11 //        }
12     }
13 
14     public static void method() {
15         int a = 10;
16         int b = 0;
17         if (b == 0) {
18             throw new ArithmeticException();
19         } else {
20             System.out.println(a / b);
21         }
22     }
23 
24     public static void method2() throws Exception {
25         int a = 10;
26         int b = 0;
27         if (b == 0) {
28             throw new Exception();
29         } else {
30             System.out.println(a / b);
31         }
32     }
33 
34 }

运行结果如下:

上面调用method方法中,由于b==0,那么就会出现如下:

throw new ArithmeticException();  就会打印下面的信息

 

 

 

当然也可以throw new ArithmeticException("我错了");  就会打印下面的信息

 

(2)

 1 package com.himi.throwdemo;
 2 
 3 public class ExceptionDemo2 {
 4     public static void main(String[] args) {
 5          //method();
 6         //调用者调用method2()方法,try……catch捕获处理异常。
 7         try {
 8             method2();
 9         } catch (Exception e) {
10             // TODO 自动生成的 catch 块
11             System.out.println("catch语句块处理捕获的异常");
12         }
13     }
14 
15     public static void method() {
16         int a = 10;
17         int b = 0;
18         if (b == 0) {
19             throw new ArithmeticException("我错了");
20         } else {
21             System.out.println(a / b);
22         }
23     }
24 
25     public static void method2() throws Exception {//这里method2抛出异常Exception,交给调用者处理
26         int a = 10;
27         int b = 0;
28         if (b == 0) {
29             throw new Exception();//这里是抛出是new Exception(异常的超类),它是编译时期异常,必须处理(上抛)
30         } else {
31             System.out.println(a / b);
32         }
33     }
34 
35 }

 运行程序,效果如下:

 

3.throws和throw的区别(面试题)

    throws(异常抛出,不处理

                    用在方法声明后面,跟的是异常类名

                    可以跟多个异常类名,用逗号隔开

                    表示抛出异常,由该方法的调用者来处理

                    throws表示出现异常的一种可能性,并不一定会发生这些异常

     throw(异常处理,打印信息

                    用在方法体内,跟的是异常对象名

                    只能抛出一个异常对象名

                    表示抛出异常,由方法体内的语句处理

                    throw则是抛出了异常,执行throw则一定抛出了某种异常

posted on 2015-09-28 16:25  鸿钧老祖  阅读(252)  评论(0编辑  收藏  举报

导航