views:

115

answers:

4

I'm trying to handle an FileNotFoundException in Java by suspending the thread for x seconds and rereading the file. The idea behind this is to edit properties during runtime.

The problem is that the programm simply terminates. Any idea how to realize this solution?

+1  A: 

Do the file loading in a loop and set the variable the condition depends on after the file has been successfully read. Use a try-catch block inside the loop and do the waiting in the catch-block.

Joachim Sauer
thanks Joachim, this should do the trick :) so obvious I should get my head checked ...
Hoggy
A: 

If the Exception is never caught, the thread is terminated. If this is your main thread, the application ends. Try the following:

try
{
   props.load(...);
}
catch (FileNotFoundException ex)
{
   Thread.sleep(x * 1000);
   props.load(...);
}
Mnementh
This will retry only once, and if I understood correctly, the idea is to retry until success.
Little Bobby Tables
Yes, a loop as you provided in your answer is a better solution. My answer basically answers the question.
Mnementh
+1  A: 

There's a good-old recipe, originally by Bjarne Stroustroup for C++, ported here to Java:

Result tryOpenFile(File f) {
  while (true) {
    try {
      // try to open the file
      return result; // or break
    } catch (FileNotFoundException e) {
      // try to recover, wait, whatever
    }
  }
}
Little Bobby Tables
`return result` is invalid for methods of type `void`.
Kevin Brock
This is pseudo-code, and yet, I stand corrected.
Little Bobby Tables
A: 

Some code snippets would be useful, but one of the following could be the problem:

  • Your code successfully catches the first FileNotFoundException but after waking up the code does not successfully handle a second one
  • Another exception is being thrown which is not being handled. Try temporarily wrapping the code in question with a catch (Exception e) to see what exception is being thrown
  • The program you use to edit the file is 'locking' the properties file and possbily preventing access by your Java code.

Good luck

Chris Knight