Catch 顶级父类Exception可以捕获所有的异常
class MyException extends Exception
{void test(){
System.out.println("test");
}
}
public class NewTest
{
public static void main(String[] args) throws Exception
{
try
{
throw new MyException();
} catch(MyException e)
{
System.out.println("xx");
}
catch(Exception e) / /捕获异常基类,可以捕获所有的异常。
{
//e.test();
System.out.println("tt");
}
finally{ //Finally处理
System.out.println("dd");
}
System.out.println("NewTest");
}
}
子类只能抛出基类方法的异常,有了这个限制,基类才可以当做子类来使用。
但是如果祖父类抛出异常,父类没有抛出异常,则本身也不能抛出异常。异常的抛出是不会继承的。但是有限制。
只能在代码中忽略RuntimeException类型的异常,其他类型的一场的处理是由编译器强制要求编程者捕获的。
异常丢失情况:
try{
throw new RuntimeException();
}finally{
doSomething;
}
这种写法中不管抛出了什么异常,都会被忽略掉。
try{
throw new RuntimeException
}finally{
return; //这个返回值后,抛出的异常就无效了。
}
既继承父类异常又实现接口的不同异常,则子类的异常不可再重新声明,因为不管修改哪一个都不符合上述规则,即如果是父类的基础上加上了接口的则属于比父类多,相对于接口亦是如此。
class Father
{
void event() throws FatherException{}
}
interface IFather
{
void event() throws FatherException222{}
}
class sub extends Father implements IFather
{
void event(){} //这里是不能再throws FatherException或FatherException222或其他的,不管怎么声明都是大于父类的。
}
<完>