2013-05-10 131 views
0

这可能看起来像一个奇怪的问题,但如果在堆栈跟踪中存在filenotfoundexception,是否可以“捕获”(知道)?我问这是因为我正在执行的类(不是我的)不会抛出异常,它会捕获它并打印堆栈跟踪。在堆栈跟踪中捕获FileNotFound?

因此,换句话说,当filenotfoundexception位于堆栈跟踪中时,是否可以使用自定义消息显示JOptionPane?

谢谢!

+0

您可能能够预先检查文件是否存在。 – Dukeling 2013-05-10 15:07:17

+1

是的,我可以,但为什么要运行代码两次? – problemo 2013-05-10 15:11:57

+0

在运行代码之前,您只需进行一次合理的快速检查。不能保证一直工作,因为可以在检查和运行代码之间以毫秒为单位(或希望在该时间段内)删除文件(您可以以某种方式将其锁定为解决方法),但可能比一些巫术魔术简单得多,以重定向标准错误输出(如果可能的话),并执行像“FileNotFoundException”之类的字符串搜索。 – Dukeling 2013-05-10 15:22:41

回答

1

下面是使用System.setErr和管道流的方法:
(这是完全有可能的,有一个更好的办法,或者它可以简化)

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

请注意,可能不建议在同一个线程中连接流,或者至少有一个必须非常小心,因为可能会很容易地陷入死锁。

但一个更简单:

file.isFile() && file.canRead() 

函数调用之前,而不是100%可靠(呼叫持续时间的工作,各地通过locking the file是可能的),是首选。

0

我试试吧:

[不是你的类打印堆栈跟踪:]

catch (Exception e) { 
     String trace = e.toString(); 
     // there are better methods than toString() in newer JDK versions, 
     // but for now it should work 
     if (trace.toLowerCase().indexOf("filenotfoundexception") >= 0) { 
     // there is one 
     JOptionPane....what ever you want... 
     } 
    } 

更新:

你不会得到抑制异常http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#getSuppressed() 但我强烈假设你FileNot ...异常不是其中之一...

+0

我在哪里可以抓到?就像我说过的,我的课没有try/catch块,因为其他类正在捕获它而不是抛出它。 – problemo 2013-05-10 15:13:39