捕获运行时错误Java

时间:2013-07-03 06:37:43

标签: java exception logging runtime-error

我相信这肯定早些时候已被提出过,但我无法搜索帖子。

我想捕获线程与本机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 个答案:

答案 0 :(得分:4)

抓住异常吧!我的猜测是,目前您的main方法被声明为抛出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...
}

有关例外的详情,请参阅exceptions part of the Java tutorial

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

答案 1 :(得分: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 Tutorials- Lesson: Exceptions

答案 2 :(得分:1)

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

答案 3 :(得分:1)

其良好做法使用try catchfinally

try {
     //Your code goes here    

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