70 lines
1.9 KiB
Java
70 lines
1.9 KiB
Java
|
// 当出现继承关系时,异常处理中要注意下面三中情况:
|
|||
|
// * A:子类重写父类方法时,子类的方法必须抛出相同的异常或父类异常的子类。
|
|||
|
// * B:如果父类抛出了多个异常,子类重写父类时,只能抛出相同的异常或者是他的子集,子类不能抛出父类没有的异常
|
|||
|
// * C:如果被重写的方法没有异常抛出,那么子类的方法绝对不可以抛出异常,如果子类方法内有异常发生,那么子类只能try,不能throws。
|
|||
|
// 请在下面代码的基础上,通过增加、修改代码对上面三种情况进行测试。
|
|||
|
|
|||
|
package exp9;
|
|||
|
|
|||
|
import java.io.FileReader;
|
|||
|
import java.io.IOException;
|
|||
|
import java.text.ParseException;
|
|||
|
import java.text.SimpleDateFormat;
|
|||
|
import java.util.Date;
|
|||
|
|
|||
|
public class ExceptionDemo {
|
|||
|
public static void main(String[] args) {
|
|||
|
Fu o = new Zi();
|
|||
|
try{
|
|||
|
o.show();
|
|||
|
o.method2();
|
|||
|
o.method();
|
|||
|
}catch(Exception e){
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
}
|
|||
|
|
|||
|
class Fu {
|
|||
|
public void show() throws Exception {
|
|||
|
}
|
|||
|
|
|||
|
public void method() {
|
|||
|
}
|
|||
|
|
|||
|
public void method2() throws Exception{
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
|
|||
|
class Zi extends Fu {
|
|||
|
@Override
|
|||
|
// public void show() throws Exception{
|
|||
|
// [* A]
|
|||
|
public void show() throws ArithmeticException {
|
|||
|
System.out.println(1/0);
|
|||
|
}
|
|||
|
|
|||
|
@Override
|
|||
|
//[* B]
|
|||
|
public void method2() throws IOException, ArrayIndexOutOfBoundsException/*, RuntimeException*/{
|
|||
|
new FileReader("NotExistFile").close();
|
|||
|
int[] arr = new int[3];
|
|||
|
System.out.println(arr[5]);
|
|||
|
}
|
|||
|
|
|||
|
//测试throws和try方法
|
|||
|
// [* C]
|
|||
|
@Override
|
|||
|
public void method()/*throws ParseException*/{
|
|||
|
try{
|
|||
|
String s = "2014-11-20";
|
|||
|
SimpleDateFormat sdf = new SimpleDateFormat();
|
|||
|
Date d = sdf.parse(s);
|
|||
|
System.out.println(d);
|
|||
|
}catch(ParseException e){
|
|||
|
System.out.println("解析日期格式失败!");
|
|||
|
}
|
|||
|
|
|||
|
}
|
|||
|
}
|