1

我敢肯定这一定是早些时候问过的,但我无法搜索该帖子。

我想用本地 java 库捕获线程生成的运行时错误,我可以用什么方法来做同样的事情?

这是一个错误示例:

Exception in thread "main" java.io.FileNotFoundException: C:\Documents and Settings\All Users\Application Data\CR2\Bwac\Database\BWC_EJournal.mdb (The system cannot find the path specified)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:106)
    at java.io.FileInputStream.<init>(FileInputStream.java:66)
    at CopyEJ.CopyEJ.main(CopyEJ.java:91)

我想将此错误记录在文件中以供稍后查看

4

4 回答 4

4

抓住异常!我的猜测是,目前你的main方法被声明为 throw Exception,而你没有捕捉到任何东西......所以异常只是从main. 抓住异常:

try {
    // Do some operations which might throw an exception
} catch (FileNotFoundException e) {
    // Handle the exception however you want, e.g. logging.
    // You may want to rethrow the exception afterwards...
}

有关异常的更多信息,请参阅Java 教程的异常部分。

在本机代码中出现异常的事实在这里无关紧要 - 它以完全正常的方式传播。

于 2013-07-03T06:39:57.783 回答
2

Thread class has 'uncaught exception handler' - see http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#setUncaughtExceptionHandler%28java.lang.Thread.UncaughtExceptionHandler%29. It allows you to delegate exception handling to somewhere outside of your thread, so you don't need to put try-catch in your run() method implementation.

于 2013-07-03T06:46:33.507 回答
1

其良好做法使用try catchfinally

try {
     //Your code goes here    

 } catch (Exception e) {
    //handle exceptions over here
} finally{
   //close your open connections
}
于 2013-07-03T06:47:18.483 回答
1

您可以使用try block.

例子

try {
    // some i/o function
    reader = new BufferedReader(new FileReader(file));

} catch (FileNotFoundException e) {
    // catch the error , you can log these
    e.printStackTrace();

} catch (IOException e) {
    // catch the error , you can log these
   e.printStackTrace();
}

Java 教程 - 课程:异常

于 2013-07-03T06:41:50.483 回答