黑马程序员技术交流社区

标题: 一个编译错误,什么原因啊 [打印本页]

作者: Rockray    时间: 2013-10-31 09:16
标题: 一个编译错误,什么原因啊
  1. class ExceptionDemo3 {
  2.         public static void main(String[] args){
  3.                 Demo d = new Demo();

  4.                 int f = d.div(5,0);   
  5.                 System.out.println(f);
  6.         }
  7. }

  8. class Demo {
  9.         int div(int a,int b){
  10.                 try {
  11.                         if(b == 0)  
  12.                                 throw new Exception();
  13.                 }
  14.                 catch(Exception e){
  15.                     System.out.println(e.toString());
  16.                         System.out.println("除零啦");
  17.                 }
  18.                 return a/b;
  19.                 finally {
  20.                         System.out.println("over");
  21.                 }
  22.                
  23.         }
  24. }
复制代码
编译失败:


明明是有try的啊
什么原因呢





作者: 张凡    时间: 2013-10-31 09:24
try...catch...finally语句需要紧跟着写,你中间有return a/b;不能算作一个语句。
作者: 李文帅    时间: 2013-10-31 09:52
try...catch...finally语句和if..else语句,do...while语句是一样的,都是紧跟着上一个语句块结束后的大括号写的,不能打断
而楼主的代码在catch语句块后的"return a/b;"则是把该try...catch..finally语句打断了,finally语句块相当于又重新写了一个try..catch...finally语句
而try...catch...finally语句的三种使用方式,try语句块是必须要有的,所以会报上述的错误
作者: 黄炳期    时间: 2013-10-31 10:39
已将帖子分类为“提问结束”。
若问题还没解决,可以继续提问。

作者: 胡志翔    时间: 2013-10-31 13:47
try catch finally 语句 是一个整体,是连在一起的 中间不能加 return a/b;这句




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2