子父类异常的错误,求高手。。。

李荣强 2012-08-01 11:22:02
/*
需求:
思路:
步骤:
*/
class AException extends Exception
{
AException(String message)
{
super(message);
}
}
class BException extends AException
{
BException(String message)
{
super(message);
}
}
class Father
{
void show()throws AException
{
throw new AException("AException");
}
}
class Son extends Father
{
void show()throws BException//throws 和throw语句中的异常必须是同一个异常,不可以使子父类的关系的异常;
{
throw new BException("BException");
try
{
throw new Exception();
}
catch(BException e )
{
e.printStackTrace();
}
System.out.println("Son show 方法执行");
}
}
class MyException
{
public static void main(String []args)
{
Father f=new Son();
try //
{
f.show();
}
catch(AException a )
{
a.printStackTrace();
}
finally
{
System.out.println("welcome to javaException");
}
System.out.println("welcome to javaMain");
}
}/*
需求:
思路:
步骤:
*/
class AException extends Exception
{
AException(String message)
{
super(message);
}
}
class BException extends AException
{
BException(String message)
{
super(message);
}
}
class Father
{
void show()throws AException
{
throw new AException("AException");
}
}
class Son extends Father
{
void show()throws BException//throws 和throw语句中的异常必须是同一个异常,不可以使子父类的关系的异常;
{
throw new BException("BException");
try //为什么这里出错,错误提示在下面;
{
throw new Exception();
}
catch(BException e )
{
e.printStackTrace();
}
System.out.println("Son show 方法执行");
}
}
class MyException
{
public static void main(String []args)
{
Father f=new Son();
try
{
f.show();
}
catch(AException a )
{
a.printStackTrace();
}
finally
{
System.out.println("welcome to javaException");
}
System.out.println("welcome to javaMain");
}
}

D:\javaprog\731>javac MyException.java
MyException.java:32: 错误: 无法访问的语句
try
^
1 个错误
...全文
61 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
lip009 2012-08-01
  • 打赏
  • 举报
回复
throw new BException("BException");//因为这一行执行过后,方法就退出了,后面的代码是永远不可能执行的
try //为什么这里出错,错误提示在下面;
{
throw new Exception();
}
catch(BException e )//这里也有错误,你上面try里throw的是Exception父类,这里却用BException子类catch
{//只能用父类catch子类,不能用子类catch父类
e.printStackTrace();
}

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧