日期:2014-05-20  浏览次数:20565 次

太奇怪了,方法中明明定义了有返回值,加上返回值则报错?
class   A
{
int   aa(int   a,int   b)   throws   yc
{

throw   new   yc( "测试一下 ");
return   a/b;
}
}
class   B
{
public   static   void   main(String   args[])
{
A   a=new   A();
try
{
a.aa(1,1);

}
catch(yc   e)
{
System.out.println(e.toString());
}

}
}
class   yc   extends   Exception
{
yc(String   str)
{
super(str);
}
}
好奇怪啊,我自己定义了一个异常类yc,之后A类中的aa方法中最后一行如果加上return   a/b则报错,请问是为什么啊?如不加return   a/b则
不会报错,但是我有定义aa函数的时候要求必须有返回值啊?

------解决方案--------------------
在有throw的情况下可以无return语句的
------解决方案--------------------
什么异常?

就是正常的情况下不会出现的情况

所以抛异常是要有条件的。

if(some condition){
throw Exception;
}
return value;
------解决方案--------------------
int aa(int a,int b) throws yc
{

throw new yc( "测试一下 ");
return a/b;
}

这里你手动引发异常了 导致return a/b永远都不可能被执行。。。。 错的应该是这里了
我新手 回答错了莫怪。。。
------解决方案--------------------
joejoe1991() 他说的是正确的 给分吧
------解决方案--------------------
可以尝试到一个新的技术社区回答www.nlld.net
------解决方案--------------------
int aa(int a,int b) throws yc
{

throw new yc( "测试一下 ");
return a/b;
}

这里你手动引发异常了 导致return a/b永远都不可能被执行。。。。 错的应该是这里了
我新手 回答错了莫怪。。。

----------------------
正解!

------解决方案--------------------
java中执行不到的代码是一种错误

------解决方案--------------------
int aa(int a,int b) throws yc
{

throw new yc( "测试一下 ");
return a/b;
}

这里你手动引发异常了 导致return a/b永远都不可能被执行。。。。 错的应该是这里了
我新手 回答错了莫怪。。。

----------------------
正解!
----------------------------
这个好象不对把?
这根本不会引发异常,因为你编译就不能通过,
a/b 这里不能这样写。
你非要除的话必须先把a,b都转为整型类型:
return (return Integer.parseInt(a.toString()))/(return Integer.parseInt(b.toString()))

------解决方案--------------------
int aa(int a,int b) throws yc
{

throw new yc( "测试一下 ");
return a/b;//由于上面throw了exception,所以这是不可达代码,编译不过的
}