《java编程思想》读书笔记(13)
子类覆写父类的方法时,如果父类的方法进行了异常声明了,子类可以不理会这个声明,不需要进行异常声明。
package com.vitamin.Console;
import java.lang.Throwable;
public class exceptionTest
{
public static void main(String[] args) throws Exception
{
// TODO Auto-generated method stub]
derive d = new derive();
d.process();
}
}
class myException extends Exception
{
myException()
{
super();
}
}
class base
{
public base()
{
}
public void process() throws myException
{
System.out.println("process() in base class");
throw new myException();
}
}
class derive extends base
{
public derive()
{
super();
}
public void process()
{
System.out.println("process() in derived class");
}
}
import java.lang.Throwable;
public class exceptionTest
{
public static void main(String[] args) throws Exception
{
// TODO Auto-generated method stub]
derive d = new derive();
d.process();
}
}
class myException extends Exception
{
myException()
{
super();
}
}
class base
{
public base()
{
}
public void process() throws myException
{
System.out.println("process() in base class");
throw new myException();
}
}
class derive extends base
{
public derive()
{
super();
}
public void process()
{
System.out.println("process() in derived class");
}
}
2.如果你先用父类catch掉了异常,那子类异常的catch块就不能到达,编译器就会报错:
package com.vitamin.Console;
import java.lang.Throwable;
public class exceptionTest
{
public static void main(String[] args) throws Exception
{
// TODO Auto-generated method stub]
try
{
throw new exception2();
}
catch(myException ex)
{
System.err.println(ex.getMessage().toString());
}
catch(exception2 ex)
{
System.err.println(ex.getMessage().toString());
}
}
}
class myException extends Exception
{
myException()
{
super();
}
}
class exception2 extends myException
{
public exception2()
{
super();
}
}
import java.lang.Throwable;
public class exceptionTest
{
public static void main(String[] args) throws Exception
{
// TODO Auto-generated method stub]
try
{
throw new exception2();
}
catch(myException ex)
{
System.err.println(ex.getMessage().toString());
}
catch(exception2 ex)
{
System.err.println(ex.getMessage().toString());
}
}
}
class myException extends Exception
{
myException()
{
super();
}
}
class exception2 extends myException
{
public exception2()
{
super();
}
}
这种用法编译器是会报错的,应该用防止父类屏蔽掉子类异常处理。
作者:洞庭散人
出处:http://phinecos.cnblogs.com/
本博客遵从Creative Commons Attribution 3.0 License,若用于非商业目的,您可以自由转载,但请保留原作者信息和文章链接URL。
posted on 2006-06-16 19:09 Phinecos(洞庭散人) 阅读(385) 评论(0) 编辑 收藏 举报