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
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.
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.
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
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
}
Related
I read in a Java book, that "Java will not allow you to declare a catch block for a checked exception type that cannot potentially be thrown by the try class body".
That makes sense so far.
But now I am asking myself why this code does compile:
try {
throw new Exception();
} catch (IOException e) {
} catch (Exception e) {
}
Java allows me to catch the IOException, but obviously it will never be thrown by the try-block.
Doesn't this example break the rule described in the Java book?
Java allows me to catch the IOException, but obviously it will never
be thrown by the try-block.
Because Exception is more general than IOException so the compiler understand that Exception can also be IOException.
Here is a contre example of what will happen if you try NumberFormatException instead of Exception
try {
throw new NumberFormatException();
} catch (IOException e) { // fail
} catch (Exception e) {
}
It fail because NumberFormatException is not general than IOException.
It is obvious to a programmer that reads this code, but i guess the compiler will deal with the throw statement the same way it would deal with a call to a method declared as throwing Exception, and in this case, the thrown exception could very well be an IOException.
I need to handle a particular exception and rest of all other exception which should gives us the same logging information but the level of logging should be different ( Former should be going to log.warn and the rest of them should be going to log.error)
try {
}
catch (someexception e) {
log.warn("some message")
-----some code----
}
catch(AllotherExceptions e) {
log.error("same message as above")
-----same code as above----
}
This needs to minimalized as the message is the same but need to make the rest of the code as a common code rather than writing it couple of times
You have several ways to do so. You can, as shown in previous answers, make successive catch statements like this :
try {
// Code that potentially throws multiple exceptions
}
catch (IOException ex) {
// Manage this particular exception case
}
catch (Exception ex) {
// Manage remaining exceptions
}
This way you'll be able to manage particular cases and define a point where all the exceptions related to the following actions will be managed. By putting this try statement early in your process (main loop, heavy service call...), you'll manage many exceptions but you'll not be able to manage specific cases since you won't know which particular actions threw them. By wrapping little specific actions (accessing files, requesting...), you'll be able to make very specific management of these exceptions.
As pointed in the answers, with Java >= 7 this syntax will work :
try {
// Code that potentially throws multiple exceptions
}
catch (IOException|SQLException ex) {
// Manage these particular exceptions
}
catch (Exception ex) {
// Manage remaining exceptions
}
This way is to be used when you need to manage different exceptions the exact same way. It's particularly helpful when a single action would throw different exceptions (ie accessing files) but you only want want to manage a few specific error cases in particular and not worrying about everything that can be thrown.
You can use multiple catch blocks to accomplish this, and catch Exception, the base class for all checked exceptions, last. For example:
try {
// Your code here.
} catch (SpecificException e) {
log.warn("Warning!", e);
} catch (AnotherSpecificException e) {
log.warn("Another warning!", e);
} catch (Exception e) {
log.error("Error!", e)
}
Just add several catch sections and finish with a catch all.
try {
// Some code
}
catch (IOException ex) {
logger.log(ex);
throw ex;
catch (Exception ex) {
logger.log(ex);
throw ex;
}
Read more here: Documentation
try{
//try something
} catch (SomeTypeException e){
//things
} catch (AnotherException e){
//AnotherThings
}
The following example, which is valid in Java SE 7 and later, eliminates the duplicated code:
try{
}
catch (IOException|SQLException ex) {
logger.log(ex);
throw ex;
}
since java 7 you can do a try-Multicatch
try {
new Foo("").doSomething();
} catch (Exception1 | Exception2 e) {
e.printStackTrace();
}
Like i have these two scenarios where we have to handle FileNotFoundException
Case1:
try {
FileInputStream fis = new FileInputStream("test1.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Case2:
try {
FileInputStream fis = new FileInputStream("test1.txt");
} catch (Exception e) {
e.printStackTrace();
}
In both cases printed Stack Trace is same. I would like to know the difference between both implementations and what should be preferred ?
From the docs it gives the reason:
"A subclass inherits all the members (fields, methods, and nested
classes) from its superclass. Constructors are not members, so they
are not inherited by subclasses, but the constructor of the superclass
can be invoked from the subclass."
Exception class is the parent of all the other exception class. So if you know that you are going to get the FileNotFoundException then it is good to use that exception. Making the Exception is a generic call.
This would help you understand:
So as you can see that the Exception class is at a higher hierarchy, so it means it would catch any exception other than the FileIOExcetion. But if you want to make sure that an attempt to open the file denoted by a specified pathname has failed then you have to use the FileIOExcetion.
So here is what an ideal approach should be:
try {
// Lets say you want to open a file from its file name.
} catch (FileNotFoundException e) {
// here you can indicate that the user specified a file which doesn't exist.
// May be you can try to reopen file selection dialog box.
} catch (IOException e) {
// Here you can indicate that the file cannot be opened.
}
while the corresponding:
try {
// Lets say you want to open a file from its file name.
} catch (Exception e) {
// indicate that something was wrong
// display the exception's "reason" string.
}
Also do check this: Is it really that bad to catch a general exception?
In case 2, the catch block will be run for all Exceptions that are caught, irrespective of what exception they are. This allows for handling all exceptions in the same way, such as displaying the same message for all types of exceptions.
In case 1, the catch block will be run for FileNotFoundExceptions only. Catching specific exceptions in different catch blocks allows for the handling of different exceptions in different ways, such as displaying a different message to the user.
When an exception occures the JVM throws the instance of the Exception and that instance is passed to the respective catch block , so in catch(Exception e) e is just the reference variable , but the instance it points to is of Exception thrown .
In case of catch(FileNotFoundException e) , e is also a reference variable and the instance it points to is of Exception thrown , so in both cases different reference varibales (i.e. e) are pointing to the instance of same the Exception (which is thrown) .
this is what i prefer :
try {
// some task
} catch (Exception e) {
if (e instanceof FileNotFoundException) {
// do this
}
if (e instanceof NullPointerException) {
// do this
} else {
// do this
}
}
It is a matter of what you want to intercept. With Exception you will catch any exception but with FileNotFoundException you will catch only that error case, allowing the caller to catch and apply any processing.
When you write this:
try {
FileInputStream fis = new FileInputStream("test1.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
The code inside the catch block is only executed if the exception (thrown inside the try block) is of type FileNotFoundException (or a subtype).
When you write this, on the other hand:
try {
FileInputStream fis = new FileInputStream("test1.txt");
} catch (Exception e) {
e.printStackTrace();
}
the catch block is executed for any exception (since Exception is the root type of any exception).
If your file (test1.txt) does not exist, a FileNotFoundException is thrown and both code snippets are able to catch it.
Try and change it to something like:
try {
FileInputStream fis = new FileInputStream("test1.txt");
} catch (NullPointerException e) {
e.printStackTrace();
}
and you will see that the catch block is no longer executed.
Exception class is the parent of FileNotFoundException.
If you have have provided the Exception in the catch statement, every Exception will be handled in the catch block. But if FileNotFoundException is present in catch block, only exceptions rising due to absence of a File at said source or permissions not available to read the file or any such issues which makes spoils Java's effort to read the file will be handled. All other exceptions will escape and move up the stack.
In the code snippet provided by you, it is fine to use both. But i would recommend FileNotFoundException as it points to exact issue in the code.
For more detail you can read Go Here
Don't use any of those.
Don't catch Exception. Why? Because it also catches all unchecked exceptions (ie, RuntimeExceptions and derivates). Those should be rethrown.
Don't use the old file API. Why? Because its exceptions are unreliable (FileNotFoundException can be thrown if you try and open a file to which you have no read access to for instance).
Use that:
final Path path = Paths.get("test1.txt");
try (
final InputStream in = Files.newInputStream(path);
) {
// do something with "in"
} catch (FileSystemException e) {
// fs level error: no permissions, is a directory etc
} catch (IOException e) {
// I/O error
}
You do need to catch FileSystemException before IOException since the former is a subclass of the latter. Among other possible exceptions you can have: AccessDeniedException, FileSystemLoopException, NoSuchFileException etc.
I see below code in my legacy project where i am catching different types of exception and intention is just to logg them
try {
//somecode
}
catch (ProjectExceptionException1 e) {
log.error(e.getMessage(), e);
}
catch (ProjectExceptionException2 e) {
log.error(e.getMessage(), e);
}
catch (Exception e) {
log.error(e.getMessage(), e);
}
My point is if requirement is just to log the exception(whether its checked or unchecked), above code should be replaced by below one
that makes code simple and more readable. As per my understanding there is not point of catching specific exception and doing
same stuff under all. Is n't it? Let me know if i am missing something here.
try {
//somecode
}
catch (Exception e) {
log.error(e.getMessage(), e);
}
UPDATE:- even if are throwing specific exception on UI just to display the stack trace like below. Even then it does not make sense
.Basically if we want to handle the specific exception in special way then it would make sense. Right?
try {
//somecode
}
catch (ProjectExceptionException1 e1) {
throw e1;
}
catch (ProjectExceptionException2 e2) {
throw e2;
}
catch (Exception e3) {
throw e3;
}
Yes, it is perfectly fine to replace the top block with the single catch (Exception e), as long as you are only logging and do not need any Exception-specific handling.
As of Java 7 you can catch multiple exceptions and handle them all in the same way using the syntax:
catch (ProjectExceptionException1 | ProjectExceptionException2 ex)
So, if you want to log some exceptions but act on others, you could group the behaviours in this manner, assuming that the actions you would like to perform are the same. e.g. print stack trace then log for ProjectExceptionException1 and ProjectExceptionException2, but only log for everything else.
If you can upgrade the code to java 1.7, you could use the new multi-catch feature. It could look like this:
try {
//somecode
}
catch (ProjectExceptionException1 | ProjectExceptionException2 e) {
log.error(e.getMessage(), e);
}
You may want to reconsider catching Exception and only catching exceptions that you know would be thrown by the code in the try block so you don't just resort to logging unexpected exceptions.
Here's a link that goes into more detail about the feature with examples: http://www.oracle.com/technetwork/articles/java/java7exceptions-486908.html
I have the following code:
try {
DOMConfigurator.configure(url+log4j.xml);
} catch(Exception e) {
e.printStackTrace();
}
And I would expect a FileNotFoundException if the log4j.xml doesn't exist, and then the catch-block would be executed.
But I don't see an exception when the file doesn't exist, why is that?
If you look at the source of DOMConfigurator.doConfigure it looks like it catches Exception and then just logs the error rather than rethrowing it. Therefore the FileNotFoundException will not make it back to your calling code.
try {
...
} catch (Exception e) {
if (e instanceof InterruptedException || e instanceof InterruptedIOException) {
Thread.currentThread().interrupt();
}
// I know this is miserable...
LogLog.error("Could not parse "+ action.toString() + ".", e);
}
To work around this you could preemptively check if the file exists yourself.
Try catching a Throwable instead of an Exception and do a print stack trace. That way you can catch any errors or exceptions and change your code accordingly.
In case you want to disable those messages from log4j, you can set log4j in quiet mode:
LogLog.setQuietMode(true);