Here are my assumptions based on your question and your clarification:
- Each thread, in the
run()
method, only calls searchfile()
once and not in a loop
- your
searchfile()
method has a loop in it and you want that loop to continue running even if an exception is thrown in it.
- you have some way of initializing each thread that you aren't showing us (and that isn't terribly important for this specific quiestion)
searchfile()
does not declare that it throws any Exception
- You aren't using a logging framework, but are instead using
System.out
(although using a logging framework is a Really Good Idea
- Java 5 is OK (otherwise you'll have to use a different
for()
loop below
With these assumptions, you don't want to plan to catch an Exception
in your run()
method except for the purpose of logging that something went very wrong:
public void run() {
try {
searchfile();
} catch (RuntimeException e) {
System.out.println("Something went very wrong! Unexpected RuntimeException");
e.printStackTrace();
}
}
Note that the code catches RuntimeException
. Always catch the most specific Exception
that will do what you need. Then what you need is something such as the following in your searchfile()
method:
File[] files = directory.listFiles();
for (File file : files) {
try {
// Do your normal file/directory processing here
} catch (Exception e) {
System.out.println("Exception processing file " + file.getName() + " " + e);
// Move "file" to another area
}
}
Since you are trapping unexpected Exception
s in the main loop of your Thread
, your thread will continue processing after handling the Exception
.