📜  Java - 继承中构造函数的异常处理

📅  最后修改于: 2022-05-13 01:55:43.637000             🧑  作者: Mango

Java - 继承中构造函数的异常处理

Java提供了一种处理异常的机制。要了解异常处理,可以参考Java的异常。在本文中,我们将讨论涉及继承时的构造函数异常处理。在Java,如果父类的构造函数抛出任何已检查的异常,那么子类的构造函数可以抛出相同的异常或其父类。如果父类或子类构造函数抛出任何未经检查的异常,则没有问题。子类构造函数可以抛出任何 未经检查的异常 无需寻找父类构造函数。

理解构造函数调用的行为

每当抛出某些异常的方法被另一个方法调用时,调用方法负责处理该异常(调用方法是包含实际调用的方法;被调用方法是被调用的方法)。在构造函数的情况下,父类构造函数由子类构造函数调用。这意味着子类构造函数负责处理父类构造函数抛出的异常。

现在,处理异常有两种方法,一种是捕获异常,另一种是抛出异常。但是在构造函数的情况下,我们无法使用 try-catch 机制来处理它。原因是我们将可以引发异常的代码包含在 try 块中,然后捕获它。由于调用父类构造函数(如 super())而引发异常。这意味着我们是否想使用 try-catch 处理异常如下图所示。

图 1



Child() {

    // Try- catch block 
    try 
    {
        super();
    } 
    
    catch (FileNotFoundException exc) 
    {
      // Handling exception(code)
    }
}

实际上,它是不正确的,因为调用 super 必须是子类构造函数中的第一条语句(在Java引用 super 可以从下图看出如下:

图二

Child() {
   super(); // either called explicitly or added by the compiler in case of default constructor
   try {
       // your code 
      }
      catch(FileNotFoundException exc) {
       // handling code;  
      }
  }

因此无法捕获异常(因为它不在 try 块内)并且我们无法使用 try-catch 机制处理它。这就是为什么我们需要抛出异常。下面的代码将编译正常,将显示如下:

// parent class constructor throws FileNotFoundException 
Child() throws FileNotFoundException  {
  super(); // either called explicitly or added by the compiler in case of default constructor
  try {
      // your code
     }
     catch(FileNotFoundException exc) {
      // handling code;  
     }
 }

不同的用例:

  1. 父类构造函数不抛出任何检查异常
  2. 父类构造函数抛出已检查异常

现在让我们详细讨论每种情况,同时通过干净的Java程序进行论证。

情况一:父类构造函数不抛出任何检查异常

如果父类构造函数没有抛出任何异常,那么子类可以抛出任何异常或什么也不抛出。

示例 1



Java
// Java Program to Illustrate Exception handling with
// Constructors in inheritance where Parent class
// constructor does not throw any checked exception
  
// Class 1
// Parent class
class Parent {
  
    // Constructor of Parent class
    // Not throwing any checked exception
    Parent()
    {
  
        // Print statement whenever parent class
        // constructor is called
        System.out.println("parent class constructor");
    }
}
  
// Class 2
// Child class
public class Child extends Parent {
  
    // Constructor of child class
    Child()
    {
  
        // Print statement whenever child class
        // constructor is called
        System.out.println("child class constructor");
    }
  
    // main driver method
    public static void main(String[] args)
    {
  
        // Creating object of child class inside main()
        Child child = new Child();
    }
}


Java
// Java Program to Illustrate Exception handling with
// Constructors in inheritance where Parent class
// constructor does not throw any checked exception
  
// Class 1
// Parent class
class Parent {
  
    // Constructor of parent class
    // Not throwing any checked exception
    Parent()
    {
  
        // Print statement when constructor of
        // parent class is called
        System.out.println("parent class constructor");
    }
}
  
// Class 2
// Child class 
public class Child extends Parent {
    Child() throws Exception
    {
  
        // Print statement when constructor of
        // child class is called
        System.out.println(
            "child class constructor throwing Exception");
    }
  
    // Main driver method
    public static void main(String[] args) throws Exception
    {
  
        // Creating object of child class
        Child child = new Child();
    }
}


Java
// Java Program to Illustrate Exception handling with
// Constructors in inheritance where Child class constructor
// Not throwing exception of same type or its parent classes
  
// Importing I/O classes
import java.io.*;
  
// Class 1
// Parent class
class Parent {
  
    // Constructor of parent class
    // Throwing checked exception
    Parent() throws FileNotFoundException
    {
  
        // Print statement when
        // parent class constructor is called
        System.out.println(
            "parent class constructor throwing exception");
    }
}
  
// Class 2
// Child class
class Child extends Parent {
  
    // Constructor of child class
    Child()
    {
        // Print statement when
        // child class constructor is called
        System.out.println("child class constructor");
    }
  
    // Main driver method
    public static void main(String[] args) throws Exception
    {
        // Creating object of child class inside main()
        Child child = new Child();
    }
}


Java
// Java Program to Illustrate Exception handling with Constructors
// in Inheritance where we Resolve the Error we Need to
// Declare the Exceptions to be Thrown
  
// Importing I/O classes 
import java.io.*;
  
// Parent class 
class Parent {
    
    // throwing checked exception
    Parent() throws FileNotFoundException {
        
        System.out.println("parent class constructor throwing checked exception");
    }
}
  
public class Child extends Parent {
    
    Child() throws FileNotFoundException {
        
        System.out.println("child class constructor throwing same exception");
    }
  
    public static void main(String[] args) throws Exception {
        
        Child child = new Child();
    }
}


Java
// Java Program to Illustrate Exception handling with
// Constructors in Inheritance where we Resolve the Error we
// Need to Declare the Exceptions to be Thrown
  
// Importing I/O classes
  
// Importing package
package package1;
// Importing required I/O classes
import java.io.*;
  
// Class 1
// Parent class
class Parent {
  
    // throwing checked exception
    Parent() throws FileNotFoundException
    {
        System.out.println(
            "parent class constructor throwing checked exception");
    }
}
  
// Class 2
// Child class
public class Child extends Parent {
  
    // It can also throw same exception or its parent
    // classes exceptions
    Child() throws IOException
    {
  
        System.out.println(
            "child class constructor throwing super-class exception");
    }
  
    // Main driver method
    public static void main(String[] args) throws Exception
    {
  
        // Creating object of child class
        // inside main() method
        Child child = new Child();
    }
}


输出
parent class constructor
child class constructor

示例 2

Java

// Java Program to Illustrate Exception handling with
// Constructors in inheritance where Parent class
// constructor does not throw any checked exception
  
// Class 1
// Parent class
class Parent {
  
    // Constructor of parent class
    // Not throwing any checked exception
    Parent()
    {
  
        // Print statement when constructor of
        // parent class is called
        System.out.println("parent class constructor");
    }
}
  
// Class 2
// Child class 
public class Child extends Parent {
    Child() throws Exception
    {
  
        // Print statement when constructor of
        // child class is called
        System.out.println(
            "child class constructor throwing Exception");
    }
  
    // Main driver method
    public static void main(String[] args) throws Exception
    {
  
        // Creating object of child class
        Child child = new Child();
    }
}
输出
parent class constructor
child class cosntructor throwing Exception

情况二:父类构造函数抛出受检异常

如果父类构造函数抛出已检查异常,则子类构造函数可以抛出相同的异常或其超类异常。现在,子类构造函数必须抛出异常。

例子

Java

// Java Program to Illustrate Exception handling with
// Constructors in inheritance where Child class constructor
// Not throwing exception of same type or its parent classes
  
// Importing I/O classes
import java.io.*;
  
// Class 1
// Parent class
class Parent {
  
    // Constructor of parent class
    // Throwing checked exception
    Parent() throws FileNotFoundException
    {
  
        // Print statement when
        // parent class constructor is called
        System.out.println(
            "parent class constructor throwing exception");
    }
}
  
// Class 2
// Child class
class Child extends Parent {
  
    // Constructor of child class
    Child()
    {
        // Print statement when
        // child class constructor is called
        System.out.println("child class constructor");
    }
  
    // Main driver method
    public static void main(String[] args) throws Exception
    {
        // Creating object of child class inside main()
        Child child = new Child();
    }
}

输出

error: unreported exception FileNotFoundException; must be caught or declared to be thrown
    Child() {
            ^

示例 1



Java

// Java Program to Illustrate Exception handling with Constructors
// in Inheritance where we Resolve the Error we Need to
// Declare the Exceptions to be Thrown
  
// Importing I/O classes 
import java.io.*;
  
// Parent class 
class Parent {
    
    // throwing checked exception
    Parent() throws FileNotFoundException {
        
        System.out.println("parent class constructor throwing checked exception");
    }
}
  
public class Child extends Parent {
    
    Child() throws FileNotFoundException {
        
        System.out.println("child class constructor throwing same exception");
    }
  
    public static void main(String[] args) throws Exception {
        
        Child child = new Child();
    }
}

输出

parent class constructor throwing checked exception
child class constructor throwing same exception

示例 2

Java

// Java Program to Illustrate Exception handling with
// Constructors in Inheritance where we Resolve the Error we
// Need to Declare the Exceptions to be Thrown
  
// Importing I/O classes
  
// Importing package
package package1;
// Importing required I/O classes
import java.io.*;
  
// Class 1
// Parent class
class Parent {
  
    // throwing checked exception
    Parent() throws FileNotFoundException
    {
        System.out.println(
            "parent class constructor throwing checked exception");
    }
}
  
// Class 2
// Child class
public class Child extends Parent {
  
    // It can also throw same exception or its parent
    // classes exceptions
    Child() throws IOException
    {
  
        System.out.println(
            "child class constructor throwing super-class exception");
    }
  
    // Main driver method
    public static void main(String[] args) throws Exception
    {
  
        // Creating object of child class
        // inside main() method
        Child child = new Child();
    }
}

输出

parent class constructor throwing checked exception
child class constructor throwing super-class exception