Java 带有异常处理的方法覆盖
原文:https://www.studytonight.com/java/methodoverriding-with-exception-handling.php
用异常处理覆盖方法时,需要记住的事情很少,因为超类的方法可能声明了异常。在这种情况下,可能有两种情况:超级类的任何一种方法都可以声明异常或不声明异常。
如果超类方法声明了异常,那么子类的方法可以声明相同的异常类、子异常类或无异常,但不能是异常类的父类。
例如,如果超类的方法声明了算术异常,那么子类的方法可以声明算术异常,它的子类或者没有异常,但是不能声明它的超/父类,比如:异常类。
在其他情况下,如果超类方法没有声明任何异常,那么子类 overriden 方法不能声明选中的异常,但是它可以声明未选中的异常。让我们看一个例子。
具有选中异常的子类中的方法覆盖
Checked exception 是预期或已知在编译时发生的异常,因此它们必须在编译时处理。
import java.io.*;
class Super
{
void show() {
System.out.println("parent class");
}
}
public class Sub extends Super
{
void show() throws IOException //Compile time error
{
System.out.println("parent class");
}
public static void main(String[] args)
{
Super s=new Sub();
s.show();
}
}
在上例中,方法show()
在 Super 类中声明/定义时不会抛出任何异常,因此其在类 Sub 中的覆盖版本也不会抛出任何选中的异常。
如果我们尝试这样做,我们将会得到一个编译时错误。
使用未检查的异常在子类中覆盖方法
未检查的异常是扩展类RuntimeExeption
的异常,并且由于某些运行时错误而引发。
import java.io.*;
class Super
{
void show() {
System.out.println("parent class");
}
}
class Sub extends Super
{
void show() throws ArrayIndexOutOfBoundsException
{
System.out.println("child class");
}
public static void main(String[] args)
{
Super s = new Sub();
s.show();
}
}
儿童班
因为ArrayindexOutofBoundSexception是一个未检查的异常,因此,覆盖的show()
方法可以抛出它。
关于覆盖方法和异常的更多信息
如果超类方法抛出异常,那么 Subclass overriden 方法可以抛出相同的异常或者不抛出异常,但是不能抛出超类方法抛出的异常的父异常。
也就是说,如果 Super 类方法抛出 NullPointerException 类的对象,那么 Subclass 方法要么可以抛出相同的异常,要么可以不抛出异常,但是它永远不能抛出异常类的对象(NullPointerException 类的父类)。
具有相同异常的子类覆盖方法的示例
子类的方法可以声明与超类中声明的相同的异常。见下面的例子。
import java.io.*;
class Super
{
void show() throws Exception
{ System.out.println("parent class"); }
}
public class Sub extends Super {
void show() throws Exception //Correct
{ System.out.println("child class"); }
public static void main(String[] args)
{
try {
Super s=new Sub();
s.show();
}
catch(Exception e){}
}
}
儿童班
无异常的子类覆盖方法示例
在覆盖期间,在子类中声明异常是可选的。如果超类的方法声明了一个异常,那么该由子类来声明异常与否。见下面的例子。
import java.io.*;
class Super
{
void show() throws Exception
{ System.out.println("parent class"); }
}
public class Sub extends Super {
void show() //Correct
{ System.out.println("child class"); }
public static void main(String[] args)
{
try {
Super s=new Sub();
s.show();
}
catch(Exception e){}
}
}
儿童班
具有父异常的子类覆盖方法的示例
不允许在子类方法中声明父类异常,如果我们试图编译那个程序,我们会得到编译时错误。见下面的例子。
import java.io.*;
class Super
{
void show() throws ArithmeticException
{ System.out.println("parent class"); }
}
public class Sub extends Super {
void show() throws Exception //Compile time Error
{ System.out.println("child class"); }
public static void main(String[] args)
{
try {
Super s=new Sub();
s.show();
}
catch(Exception e){}
}
}
编译时错误