0

Is there a way to handle an exception in the constructor. Everytime I use the getter into another method I have to declare the exception again. I tried a try/catch block inside the constructor but still asking for other method to declare the exception.

public Question() {
    try {
        this.file = new File("questions.txt");
    } catch (Exception e) {
        System.out.println("Could not find file");
        System.out.println("Check file path is correct");
    }
    counterIndex = 0;
    questionSetup();
}

public Question() throws FileNotFoundException {
    file = new File("questions.txt");
    counterIndex = 0;
    questionSetup();
}

public ArrayList<String> getQuestionArr() {
    return questionArr;
}

public File getFile() {    
    return file;
}
Vy Do
  • 46,709
  • 59
  • 215
  • 313
JPark
  • 1
  • 2
  • AFAIK constructors handle try catch blocks just like any other code. Are you sure you put the try catch in the right place ? –  Apr 12 '15 at 05:31
  • Yeah the first one has the try catch/block and the second one doesnt, not sure though if its properly placed – JPark Apr 12 '15 at 05:35
  • Why do you have two identical constructors in the example? I don't understand if you have a try-catch block why would it ask you to declare the exception? Could you post the code that actually makes you do this? –  Apr 12 '15 at 05:55
  • the first one is just showing where i put the try and catch block, the second is without it. In my class there's only one – JPark Apr 12 '15 at 05:57

1 Answers1

0

Throw it from the constructor, and handle it anywhere else. When a constructor encounters an exceptional situation, it should throw an exception instead of continuing along and fully constructing an object.

Imagine if FileInputStream didn't throw a FileNotFoundException.

FileInputStream fis = new FileInputStream("~/iDontReallyExist.bin");
// appears to work

// then later, long after you've instantiated `fis`
fis.read(buffer); // <-- boom?

Constructors can and should throw exceptions whenever something breaks. Code calling the constructor (or higher up in the stack) handle it as they see fit (trying again, failing, etc.). As a bonus, the half constructed object becomes available for garbage collection without you needing to be too concerned about it.

Assuming that Question() throws a FileNotFoundException, you can handle an error something like this (I don't know your real app obviously, so this is made up as an example of error handling):

Question loadQuestion(int id) throws FileNotFoundException { 
    return new Question(getQuestionPath(id)); 
}

called by:

Set<Question> getQuestionsByCategory(QuestionCategory category) { 
    Set<Integer> ids = getQuestionIds(category); 
    Set<Question> questions = new HashSet<Question>();
    for (Integer id : ids) { 
        try { 
            questions.add(loadQuestion(id));
        } catch (FileNotFoundException ex) { 
            somelogger("File not found loading question ID " + id, ex);
            throw ex; 
        }
    }
    return questions;
}

and finally

public static void main(String[] args) throws FileNotFoundException { 
    Set<Questions> questions = QuestionsLoader
       .getQuestionsByCategory(QuestionCategory.valueOf(args[0]));
}

In this example, I log it in code responsible for loading questions by category, then re-throw it to let it blow up. I chose to do that because not being able to open a local file seems like something fatal here, but you're not constrained to do that. You could instead simply not include the question in the returned results, or ask for a different path to search. The bottom line of what to do upon an error is ultimately in context of what you need.

Community
  • 1
  • 1
jdphenix
  • 15,022
  • 3
  • 41
  • 74
  • does that mean i use the second constructor then use try/catch block into another method that uses (in this case getter) and handle it there??. Thanks for the input – JPark Apr 12 '15 at 06:05
  • Thanks finally understood what you're trying to say after 3days of reading. Why i cant give kudos btw – JPark Apr 14 '15 at 04:01