子父类异常的错误,求高手。。。
/*
需求:
思路:
步骤:
*/
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 个错误
------解决方案--------------------
throw new BException("BException");//因为这一行执行过后,方法就退出了,后面的代码是永远不可能执行的
try //为什么这里出错,错误提示在下面;
{
throw new Exception();
}
catch(BException e )//这里也有错误,你上面try里throw的是Exception父类,这里却用BException子类catch
{//只能用父类catch子类,不能用子类catch父类
e.printStackTrace();
}