Here's a way using System.setErr
and piped streams:
(it's entirely possible that there's a better way or it can be simplified)
public static void badFunctionCall()
{
new FileNotFoundException("The file could not be found!").printStackTrace();
}
public static void main(String[] args) throws IOException
{
PipedOutputStream writer = new PipedOutputStream();
PipedInputStream reader = new PipedInputStream(writer);
PrintStream p = new PrintStream(writer);
System.setErr(p);
badFunctionCall();
p.close(); // do this *before* reading the input stream to prevent deadlock
int c;
StringBuilder builder = new StringBuilder();
while ((c = reader.read()) != -1)
builder.append((char)c);
if (builder.toString().contains("java.io.FileNotFoundException: "))
System.out.println("An error occurred! Caught outside function.");
reader.close();
}
Test.
Note that it's probably not advisable to connect streams in the same thread, or at least one has to be really careful, as one can very easily run into deadlock.
But a much simpler:
file.isFile() && file.canRead()
before the function call, while not 100% reliable (a work-around by locking the file for the duration of the call may be possible), is preferred.