1. The question
In Java, methods can throw exceptions. Can constructors also throw exceptions? The answer is YES.
2. The reason and some necessary background
A constructor is just a special method. In this perspective, it surely can do what regular methods can do.
It is possible that there are some objects created and assigned to static fields before the constructor method is done. In this case, the object that should be created is not created yet. So you need to be careful about the consistency.
Here is an example constructor method that throws an exception.
class FileReader{ public FileInputStream fis = null; public FileReader() throws IOException{ File dir = new File(".");//get current directory File fin = new File(dir.getCanonicalPath() + File.separator + "not-existing-file.txt"); fis = new FileInputStream(fin); } } |
If you want to know the best practice of Java exception handling, I highly recommend this post.