构造函数可以在Java中引发异常吗?
甲构造用于创建时初始化对象。从语法上讲,它类似于一种方法。区别在于,构造函数的名称与其类相同,并且没有返回类型。
无需显式调用构造函数,这些构造函数会在实例化时自动调用。
示例
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