黑马程序员技术交流社区
标题:
异常问题
[打印本页]
作者:
左耳的鱼
时间:
2013-7-16 21:16
标题:
异常问题
本帖最后由 左耳的鱼 于 2013-7-16 23:51 编辑
public class ExceptionTest{
public double div(double a, double b){
try{
return a/b;
}catch(Exception e){
System.out.println(“Exception thrown”);
}finally{
System.out.println(“Release resources.”);
}
}
public static void main(String[] args){
ExceptionTest et = new ExceptionTest();
et.div(1, 2);
et.div(3.4, 0);
}
}
//为什么编译不成功,异常没有捕获吗???????
作者:
chslzj
时间:
2013-7-16 21:19
看代码的第一直觉是缺少return语句
作者:
王靖远
时间:
2013-7-16 21:43
没有返回值。try中出了异常的话,catch代码块中没有返回值。
作者:
牛海亮
时间:
2013-7-16 21:56
编译器认为try块中是有可能产生异常操作的,也就是说在return语句之前如果出现异常的话,那么return语句根本没有机会得到执行,所以编译器会认为缺少return语句,在catch或者finally模块中添加一个return 语句就行了。
还有就是你的代码中Exception thrown Release resources 两边的引号是中文标点符号。
我把你的代码稍微改了一下,你参考下吧。
public class ExceptionTest
{
public double div(double a, double b)
{
try
{
return a/b;
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("Exception thrown");
return -1;
}
finally
{
System.out.println("Release resources");
}
}
public static void main(String[] args)
{
ExceptionTest et = new ExceptionTest();
System.out.println(et.div(1, 2));
System.out.println(et.div(3.4, 0));
}
//为什么编译不成功,异常没有捕获吗???????
}
复制代码
作者:
straw
时间:
2013-7-16 22:55
代码中有两处错误:
1, finally 里没有return,或者将return a/b;写到finally体后,总之要保证程序无乱如何都要有返回值.
2, System.out.println(“Exception thrown”);里面的双引号是英文的双引号而不是中文的双引号.
把上面两处修改后就可以了.
作者:
周之浩
时间:
2013-7-16 23:09
你的try{}catch(){}finally{}中的return语句错误的,程序一旦遇到return语句就将当前执行的函数结束掉,而try{}catch(){}finally{}语句后没有return语句这样编译器认为没有返回值
public class ExceptionTest{
public double div(double a, double b){
double res = 0;
try{
res = a/b;
}catch(Exception e){
System.out.println("Exception thrown");
}finally{
System.out.println("Release resources.");
}
return res;
}
public static void main(String[] args){
ExceptionTest et = new ExceptionTest();
et.div(1, 2);
et.div(3.4, 0);
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2