java throw和catch同时使用

当异常出现在当前方法中,程序只对异常进行部分处理,还有一些处理需要在方法的调用者中才能处理完成,此时还应该再次抛出异常,这样就可以让方法的调用者也能捕获到异常;

 

Eg

public static void buy(String price) throws Exception {

       try {

              if(price != null)

                     Double.parseDouble(price);

       } catch (Exception e) {

              e.printStackTrace();

              throw new Exception("价格不能只能是数字组成");

       }

}

public static void main(String[] args)  {

       try {

              buy(null);

       } catch (Exception e) {

              System.out.println(e.getMessage());

       }

}

posted @ 2019-07-04 14:25  樊伟胜  阅读(1961)  评论(0编辑  收藏  举报