Constructor Can Throw Exceptions in Java!

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.

3. An Example of a constructor that throws an exception

Here is an example constructor method that throws an exception. This is a bad example, the correct way is to catch the exception and handle necessary jobs, such as reset the jobs that have been completed.

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);

In a constructor method, if we open both a FileInputStream and a FileOutputStream, and the first one succeeds and second one fails, then in the exception handling clause you need to close reset the first one.


Category >> Exceptions  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";