Reputation: 537
I am sure this must have been asked earlier, but I couldn't search the post.
I want to capture run time errors generated by thread with native java libraries, what methods can I use to do same ?
Here's an example of error :
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)
I want to log this error in file to be reviewed later
Upvotes: 1
Views: 1163
Reputation: 5366
its good practices use try
catch
and finally
try {
//Your code goes here
} catch (Exception e) {
//handle exceptions over here
} finally{
//close your open connections
}
Upvotes: 1
Reputation: 2531
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.
Upvotes: 2
Reputation: 7694
You can catch errors with the try block
.
Example
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
Upvotes: 1
Reputation: 1499860
Just catch the exception! My guess is that currently your main
method is declared to throw Exception
, and you're not catching anything... so the exception is just propagating out of main
. Just catch the exception:
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...
}
See the exceptions part of the Java tutorial for more information about exceptions.
The fact that the exception came up in native code is irrelevant here - it's propagated in a perfectly normal way.
Upvotes: 4