Exception in Constructor
In some situation it is possible that the constructor of a class throw exception. In such condition you should have proper code to handle it. In this section we will going to discuss how we handle exception thrown by a constructor.
Given below example will give you a clear idea how a constructor can throw exception and how should we handle it :
EXAMPLE
Given below a parameterized constructor which accept file name as string argument. This constructor will open the file, But if there is a problem in opening file, it will revert calling routine with a exception or simply it throw the exception back to the calling routine.
package simpleCoreJava;
import java.io.*;
class WordCount2
{
//creates BufferedReader to read/open the input file
private BufferedReader br=null;
//print writer to write to a file
private PrintWriter pw=null;
public WordCount2(String afile) throws Exception
{
File inFile=new File(afile);
//if the file the user puts in does not exist, then throw an exception
if(inFile.exists())
{
try
{
br=new BufferedReader(new FileReader(afile));
}
catch(FileNotFoundException fnfe)
{
System.out.println(fnfe.getMessage());
}
catch(IOException ioe)
{
System.out.println(ioe.getMessage());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
else
{
throw new Exception("The input file does not exist");
}
}
}
public class WordCount{
public static void main(String args[])
{
try {
WordCount2 w2= new WordCount2("C:/ankit.txt");
} catch (Exception e) {
e.printStackTrace();
}
}
}
OUTPUT
java.lang.Exception: The input file does not exist at simpleCoreJava.WordCount2.<init>(WordCount.java:42) at simpleCoreJava.WordCount.main(WordCount.java:51) |