A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 丁强强 中级黑马   /  2013-1-26 10:17  /  1069 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 张向辉 于 2013-1-27 11:01 编辑

对什么时候throws
什么时候 try
有点疑惑。

点评

建议看毕老师异常视频  发表于 2013-1-26 10:18

1 个回复

倒序浏览
这个你就这么理解,在一个方法中如果某个语句块可能出现异常,则可以使用try{}catch{}语句对其进行捕捉,在catch{}语句块中对异常进行处理,如过你还不想处理的话,你可以对这个异常进行在包装,使用throws关键字继续往上扔,交由调用这个方法的方法进行处理,不过要在原方法的上面标示抛出那种异常或该异常的父类,这样程序员调用这个方法时,就会知道我是继续用try{}catch{}对异常进行捕捉,还是我也往上扔,最后可能会在直接抛到main()方法上,main()方法是程序的起点,在main()方法后面加上throws抛出异常后直接交给jvm进行处理,届时,程序将中断,举个例子给你看吧

  1. public class TestException {

  2.         public static void main(String[] args) throws Exception {
  3.                 String str1 = "8";
  4.                 String str2 = "0";
  5.                 TestException.getResult(str1, str2);        //调用静态方法
  6.                 System.out.println("ok");
  7.                
  8.         }
  9.        
  10.         public static int getResult(String a, String b) throws Exception {        //定义一个静态方法,用于取得两数之商
  11.                 int value = 0;
  12. /*                int num1 = Integer.parseInt(a);
  13.                 int num2 = Integer.parseInt(b);
  14.                 value = num1/num2;*/
  15.                 try {
  16.                         int num1 = Integer.parseInt(a);
  17.                         int num2 = Integer.parseInt(b);
  18.                         value = num1/num2;
  19.                         System.out.println("运算结果是" + value);
  20.                        
  21.                 } catch (ArithmeticException e) {
  22.                         System.out.println(e.getMessage());                //打印出错的信息
  23.                         throw new RuntimeException("除数为0");        //第二种方式,重新包装后抛出去
  24.                        
  25.                 } catch (NumberFormatException e) {
  26.                         System.out.println(e.getMessage());  
  27.                         System.out.println(e.toString());
  28.                         e.printStackTrace();
  29.                 } catch (Exception e) {
  30.                         e.printStackTrace();
  31.                 } finally {
  32.                         System.out.println("我一定会出现的");
  33.                 }
  34.                 return value;
  35.         }

  36. }
复制代码
这样你就懂了吧

评分

参与人数 1技术分 +1 收起 理由
Rancho_Gump + 1 赞一个!

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马