Java 中的构造函数可以抛出异常吗?

java 8object oriented programmingprogramming更新于 2024/10/14 14:47:00

构造函数用于在创建对象时对其进行初始化。它在语法上类似于方法。不同之处在于构造函数与其类同名,并且没有返回类型。

无需显式调用构造函数,这些构造函数会在实例化时自动调用。

示例

public class Example {
   public Example(){
      System.out.println("This is the constructor of the class example");
   }
   public static void main(String args[]) {
      Example obj = new Example();
   }
}

输出

This is the constructor of the class example

构造函数抛出异常

是的,就像方法一样,您可以从构造函数中抛出异常。但是,如果您这样做,您需要在调用构造函数的方法中捕获/抛出(处理)异常。如果不这样做,将生成编译时错误。

示例

在下面的例子中,我们有一个名为 Employee 的类,其构造函数抛出 IOException,我们在不处理异常的情况下实例化该类。因此,如果您编译此程序,它将生成编译时错误。

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
class Employee{
   private String name;
   private int age;
   File empFile;
   Employee(String name, int age, String empFile) throws IOException{
      this.name = name;
      this.age = age;
      this.empFile = new File(empFile);
      new FileWriter(empFile).write("Employee name is "+name+"and age is "+age);
   }
   public void display(){
      System.out.println("Name: "+name);
      System.out.println("Age: "+age);
   }
}
public class ConstructorExample {
   public static void main(String args[]) {
      String filePath = "samplefile.txt";
      Employee emp = new Employee("Krishna", 25, filePath);
   }
}

编译时错误

ConstructorExample.java:23: error: unreported exception IOException; must be caught or declared to be thrown
   Employee emp = new Employee("Krishna", 25, filePath);
                  ^
1 error

示例

为了使该程序正常工作,请将实例化行包装在 try-catch 中,或者抛出异常。

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
class Employee{
   private String name;
   private int age;
   File empFile;
   Employee(String name, int age, String empFile) throws IOException{
      this.name = name;
      this.age = age;
      this.empFile = new File(empFile);
      new FileWriter(empFile).write("Employee name is "+name+"and age is "+age);
   }
   public void display(){
      System.out.println("Name: "+name);
      System.out.println("Age: "+age);
   }
}
public class ConstructorExample {
   public static void main(String args[]) {
      String filePath = "samplefile.txt";
      Employee emp = null;
      try {
         emp = new Employee("Krishna", 25, filePath);
      }catch(IOException ex) {
         System.out.println("Specified file not found");
      }
      emp.display();
   }
}

输出

Name: Krishna
Age: 25

相关文章