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函数的时候要求必须有返回值啊?

解决方案 »

  1.   

    在有throw的情况下可以无return语句的
      

  2.   

    哦,可以无return语句?但不如果在有throw方法中想返回值,应当怎么办呢?
      

  3.   

    什么异常?就是正常的情况下不会出现的情况所以抛异常是要有条件的。if(some condition){
       throw Exception;
    }
    return value;
      

  4.   

    什么叫异常?就是正常的情况下不会出现的情况所以抛异常是要有条件的。if(some condition){
    throw Exception;
    }
    return value;即使你非要往变态的整,写个:
    if(true) 也是可以的
      

  5.   

    int aa(int a,int b) throws yc
    {

    throw new yc("测试一下");
    return a/b;
    }这里你手动引发异常了 导致return a/b永远都不可能被执行。  错的应该是这里了 
    我新手 回答错了莫怪
      

  6.   

    哈哈,我怎么会怪罪于你呢,我现在是自学java现在看的是孙鑫的JAVA 视频教程.其中有相似的异常的例子,也许你说的是对我,我再测试一下.
    另外要特别的感谢malligator(不能再整天泡在CSDN里了!)
      

  7.   

    joejoe1991()    他说的是正确的    给分吧
      

  8.   

    可以尝试到一个新的技术社区回答www.nlld.net
      

  9.   

    int aa(int a,int b) throws yc
    {

    throw new yc("测试一下");
    return a/b;
    }这里你手动引发异常了 导致return a/b永远都不可能被执行。  错的应该是这里了 
    我新手 回答错了莫怪----------------------
    正解!
      

  10.   

    java中执行不到的代码是一种错误
      

  11.   

    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()))
      

  12.   

    晕,不好意思,我看错了。
    throw new yc("测试一下");这个注意,晕死。
      

  13.   

    throw new yc("测试一下");这个没注意。
      

  14.   

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