捕获运行时错误Java



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

我想用本机java库捕获线程生成的运行时错误,我可以用什么方法来做到这一点?

下面是一个错误示例:

Exception in thread "main" java.io.FileNotFoundException: C:Documents and SettingsAll UsersApplication DataCR2BwacDatabaseBWC_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)

我想把这个错误记录在文件中,以便稍后查看

只需捕获异常!我的猜测是,当前您的main方法被声明为抛出Exception,并且您没有捕获任何内容。。。所以异常只是从CCD_ 3传播出去。抓住例外:

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教程中的异常部分。

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

线程类具有"未捕获的异常处理程序"-请参阅http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#setUncaughtExceptionHandler%28java.lang.Thread.UncaughtExceptionHandler%29.它允许您将异常处理委托给线程之外的某个地方,因此您不需要在run()方法实现中放入try-catch。

您可以用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教程-课程:异常

其良好实践使用try catchfinally

try {
     //Your code goes here    
 } catch (Exception e) {
    //handle exceptions over here
} finally{
   //close your open connections
}

最新更新