Share on Google+Share on Google+

Exceptional Constructors - Java Tutorials

exceptional constructors

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 :


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;


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
br=new BufferedReader(new FileReader(afile));

catch(FileNotFoundException fnfe)

catch(IOException ioe)

catch(Exception e)

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


 java.lang.Exception: The input file does not exist
 at simpleCoreJava.WordCount2.<init>(                                                    
 at simpleCoreJava.WordCount.main(



Posted on: April 18, 2011 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: Exceptional Constructors - Java Tutorials  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image