Hello,
In Java if a method like BufferedReader.read() says it can throw an IOException and I try to catch a FileNotFoundException and an IOException in two catch blocks, what catch blocks will be entered if the file doesn't exist?
Does it enter only the most specific or both?
The first coded catch that matches the exception will be entered.
Edited to incorporate comment from Azodius
For example:
try {
bufferedReader.read();
} catch (FileNotFoundException e) {
// FileNotFoundException handled here
} catch (IOException e) {
// Other IOExceptions handled here
}
This following code does not compile:
try {
bufferedReader.read();
} catch (IOException e) {
// All IOExceptions (and of course subclasses of IOException) handled here
} catch (FileNotFoundException e) {
// Would never enter this block, because FileNotFoundException is a IOException
}
Compiler message says:
Unreachable catch block for FileNotFoundException. It is already handled by the catch block for IOException
Only the first catch block encountered where the exception type of the catch block matches the type of the exception being thrown will be run (more specifically, the first catch block where (e instaceof <exception type>)==true will be run). None of the other catch blocks will be run.
For example
try{
BufferedReader.read();
}
catch(FileNotFoundException e){System.out.println("FileNotFoundException");}
catch(IOException e){System.out.println("IOException");}
Will print FileNotFoundException if BufferedReader.read() throws a FileNotFoundException.
Note that the following doesn't actually compile:
try{
BufferedReader.read();
}
catch(IOException e){System.out.println("IOException");}
catch(FileNotFoundException e){System.out.println("FileNotFoundException");}
because Java realizes that it is not possible for the FileNotFoundException to be caught because all FileNotFoundExceptions are also IOExceptions.
The first one which is suitable for that type of exception (and only that). So if you catch the two exception types above in the order you list them, a FileNotFoundException will be caught.
Specific exception is caught first. and it's a compile time error if generic exception is caught befor specific one.
Related
This question already has answers here:
Exception thrown in catch and finally clause
(12 answers)
Closed 1 year ago.
I have this piece of Java code.
void convertFile() {
try{
.....
}catch (Exception e) {
logError("Error in convertJsonFile", e);
throw e;
}finally{
if (writer!=null) {
writer.close();
writer = null;
}
if (fos!=null) {
fos.close();
fos = null;
}
ms2 = System.currentTimeMillis();
logInfo(String.format("Time elapsed: %d seconds.", ((ms2-ms1)/1000)));
logInfo("File conversion complete.");
}
return f + "_changed.xml";
}
The catch block logs and rethrows the Exception.
But it seems the finally block also throws a RuntimeException.
Will the finally block be executed if the catch block rethrows Exception as done here?
If I remember correctly finally block will be executed even in this case.
OK if so... what will happen if we enter the catch block (it rethrows), then we enter the finally block, and the finally block also throws a RuntimeException at this line writer.close(); ? Which exception will be thrown from this whole method - the rethrown one from the catch block, or the RuntimeException from the finally block?!
I think the RuntimeException will be the final outcome of the method and we will never reach the line in the catch block which rethrows. Because I guess the line which rethrows is executed after the finally block. But I am not sure. I got really confused.
Could someone clear my doubts here?
Seems I have forgotten some of these details.
And I have no decent access to the logs, they are in Elastic/Kibana and access to them is a real pain.
Yes, finally block will be executed
The exception from finally block will be thrown in this case. Thus, exception from catch block will be lost.
I am learning how to create file and directory in java using this code.
On the ERROR LINE I am getting error as "IOException is never thrown in this block".
So how do I know which function is throwing what type of Exception?
Or if I am not sure I should use generic Exception in every catch block.
public class FileTest {
public static void main(String[] args) {
//file creation
boolean flag = false;
File file = new File("/IdeaProjects/JavaCode/jstest.txt");
try {
flag = file.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
System.out.println("file path is : " + file.getPath());
//dir creation
boolean dirFlag = false;
File fileDir = new File("/IdeaProjects/JavaCode/js");
try{
dirFlag = fileDir.mkdir();
}catch (IOException e){//ERROR LINE
e.printStackTrace();
}
if(dirFlag)
System.out.println("created");
else
System.out.println("exist");
}
}
The java.io.File#mkdir method only declares to throw SecurityException - see API.
java.lang.SecurityException is a RuntimeException and doesn't require being caught, although you may want to, depending on the context (again, see API).
Catching general java.lang.Exception in every catch block is absolutely not a recommended practice, although you may sometimes have to (not in your present case though).
See here for some SO literature on the matter.
Remember what methods throw exceptions and which exceptions they are.
Check the documentation if you think a method may throw an exception.
Just attempt to compile the code and fix the errors the compiler throws (They will tell you what exceptions are thrown by what method if the try-catch block is missing).
The method in question (File.mkdir()) throws a SecurityException which doesn't need to be caught (you can if need be) as it is an unchecked RuntimeException.
java.io.File: https://docs.oracle.com/javase/7/docs/api/java/io/File.html#mkdir()
SecurityException: https://docs.oracle.com/javase/7/docs/api/java/lang/SecurityException.html
Quoting JLS Section 11.2:
It is a compile-time error if a catch clause can catch checked exception class E1 and it is not the case that the try block corresponding to the catch clause can throw a checked exception class that is a subclass or superclass of E1, unless E1 is Exception or a superclass of Exception.
If no method you invoke in the try block declares that it throws IOException (and you don't throw new IOException(..) directly either), it is a compile-time error if you try to catch an IOException.
Background
I have a case where my logic requires surround with try/catch, I have a lots of catch clauses, which makes my code a bit ugly. What I do in catch clause is only log the error using log4j.
Question
Is it ok to use one catch clause with parent exception type instead of bunch of catch clauses?
Instead of this:
try{
//some statements
} catch (KeyStoreException e) {
LOGGER.error(e);
} catch (CertificateException e) {
LOGGER.error(e);
} catch (NoSuchAlgorithmException e) {
LOGGER.error(e);
} catch (FileNotFoundException e) {
LOGGER.error(e);
} catch (IOException e) {
LOGGER.error(e);
} catch (UnrecoverableKeyException e) {
LOGGER.error(e);
} catch (NoPropertyFoundException e) {
LOGGER.error(e);
}
using :
try{
//some statements
} catch (Exception e) {
LOGGER.error(e);
}
Which one is better?
When catch exceptions I usually find that more specific is better, that being said typing out all of those different blocks that do the same thing can get really annoying. Thankfully in the Java 7 release a try-catch notation was added where you can specific multiple exceptions for a single block:
try{
//some statements
} catch (KeyStoreException |
CertificateException |
NoSuchAlgorithmException |
FileNotFoundException |
IOException |
UnrecoverableKeyException |
NoPropertyFoundException e) {
LOGGER.error(e);
}
This sounds like what you are looking for, but there is more detailed information in the Oracle docs: http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html
Is it ok to use one catch clause with parent exception type instead of bunch of catch clauses?
Hunter has provided the correct solution for Java 7 and later.
For Java 6 and earlier, it depends on the parent exception that you choose. Exceptions like Throwable, Exception and RuntimeException are far too general. If you catch these, you can end up accidentally catching (and then mishandling) exceptions that you should allow to propagate. For example, your code would catch NullPointerException that you should probably not attempt to recover from ... like that.
The first version is more correct / more robust than the second version, and that better even if it looks ugly.
Of course, the real answer depends on what happens after you have caught and logged the exception. If what happens next is appropriate for all exceptions, then the second version is (arguably) preferable. For instance, it could be appropriate to catch all exceptions, log them and then call System.exit(...).
I have a small theoretical problem with try-catch constructions.
I took a practical exam yesterday about Java and I don't understand following example:
try {
try {
System.out.print("A");
throw new Exception("1");
} catch (Exception e) {
System.out.print("B");
throw new Exception("2");
} finally {
System.out.print("C");
throw new Exception("3");
}
} catch (Exception e) {
System.out.print(e.getMessage());
}
The question was "what the output will look like?"
I was pretty sure it would be AB2C3, BUT suprise suprise, it's not true.
The right answer is ABC3 (tested and really it's like that).
My question is, where did the Exception("2") go?
From the Java Language Specification 14.20.2.:
If the catch block completes abruptly for reason R, then the finally block is executed. Then there is a choice:
If the finally block completes normally, then the try statement completes abruptly for reason R.
If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).
So, when there is a catch block that throws an exception:
try {
// ...
} catch (Exception e) {
throw new Exception("2");
}
but there is also a finally block that also throws an exception:
} finally {
throw new Exception("3");
}
Exception("2") will be discarded and only Exception("3") will be propagated.
Exceptions thrown in finally block suppress the exception thrown earlier in try or catch block.
Java 7 example: http://ideone.com/0YdeZo
From Javadoc's example:
static String readFirstLineFromFileWithFinallyBlock(String path)
throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
}
However, in this example, if the methods readLine and close both throw
exceptions, then the method readFirstLineFromFileWithFinallyBlock
throws the exception thrown from the finally block; the exception
thrown from the try block is suppressed.
The new try-with syntax of Java 7 adds another step of exception suppression: Exceptions thrown in try block suppress those thrown earlier in try-with part.
from same example:
try (
java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);
java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
) {
for (java.util.Enumeration entries = zf.entries(); entries.hasMoreElements();) {
String newLine = System.getProperty("line.separator");
String zipEntryName = ((java.util.zip.ZipEntry)entries.nextElement()).getName() + newLine;
writer.write(zipEntryName, 0, zipEntryName.length());
}
}
An exception can be thrown from the block of code associated with the
try-with-resources statement. In the above example, an exception can
be thrown from the try block, and up to two exceptions can be thrown
from the try-with-resources statement when it tries to close the
ZipFile and BufferedWriter objects. If an exception is thrown from the
try block and one or more exceptions are thrown from the
try-with-resources statement, then those exceptions thrown from the
try-with-resources statement are suppressed, and the exception thrown
by the block is the one that is thrown by the
writeToFileZipFileContents method. You can retrieve these suppressed
exceptions by calling the Throwable.getSuppressed method from the
exception thrown by the try block.
In code from question, each block is plainly discarding the old exception, not even logging it, not good when you are trying to resolve some bugs:
http://en.wikipedia.org/wiki/Error_hiding
Since throw new Exception("2"); is thrown from catch block and not try, it won't be caught again.
See 14.20.2. Execution of try-finally and try-catch-finally.
This is what happening:
try {
try {
System.out.print("A"); //Prints A
throw new Exception("1");
} catch (Exception e) {
System.out.print("B"); //Caught from inner try, prints B
throw new Exception("2");
} finally {
System.out.print("C"); //Prints C (finally is always executed)
throw new Exception("3");
}
} catch (Exception e) {
System.out.print(e.getMessage()); //Prints 3 since see (very detailed) link
}
Your Question is very obvious, and the answer is simple to the same extent..
The Exception object with message as "2" is overwritten by the Exception object with message as "3" .
Explanation :
When an Exception occur, its object it thrown to catch block to handle. But when exception occur in catch block itself, its object is transferred to OUTER CATCH Block(if any) for exception Handling. And Same happened Here. The Exception Object with message "2" is transferred to OUTER catch Block . But wait.. Before leaving inner try-catch block it HAS TO EXECUTE FINALLY. Here occurred the change we are concerned about. A new EXCEPTION object(with message "3") is thrown out or this finally block which replaced the already thrown Exception object(with message "2").As a result of which, when the message of Exception object is printed , we got overridden value i.e. "3" and not "2".
Keep Remember :Only one exception object can be handled by on CATCH block.
The finally block always runs. Either you return from inside the try block or an exception is thrown. The exception thrown in the finally block will override the one thrown in the catch branch.
Additionally, throwing an exception will not cause any output by itself. The line throw new Exception("2"); will not write anything out.
According to your code:
try {
try {
System.out.print("A");
throw new Exception("1"); // 1
} catch (Exception e) {
System.out.print("B"); // 2
throw new Exception("2");
} finally { // 3
System.out.print("C"); // 4
throw new Exception("3");
}
} catch (Exception e) { // 5
System.out.print(e.getMessage());
}
As you can see here:
print A and throws exception # 1;
this exception has caught by catch statement and print B - # 2;
block finally # 3 executes after try-catch (or only try, if hadn't occurred any exception) statement and prints C - # 4 and thrown new exception;
this one has caught by external catch statement # 5;
Result is ABC3. And 2 is omitted at the same way as 1
I am doing an app for finding BPM in Android. Based on the input of the file null pointer exception and IO exception is getting thrown. When the exception occurs the program is terminated, even if I surround the code with a try/catch block. My requirement is that the program not terminate, and continue to the other parts.
My Code:
try {
mp3file.seekMP3Frame();
sourcefile = new File("/sdcard/a.mp3");
mp3file = new MP3File(sourcefile);
AbstractID3v2 tag = mp3file.getID3v2Tag();
text=tag.getFrame("TBPM").toString();
}
catch (NullPointerException e) {
System.out.println("null pointer exception");
}
catch (IOException e1) {
System.out.println("IO exception");
}
........ // other coding
If the error occurs between the try - catch block :
You are only catching 2 exceptions here (NullPointerException and IOException).
Any other runtime exception between the try - catch block can still cause your program to crash. catch java.lang.Throwable to ensure all exceptions are catched.
If the error doesn't occur between the try - catch block :
Look in the stacktrace for the line in your class where the error occurs, and implement "proper" error handling there.
If your application crashes, you'll always see a stacktrace in logcat. That stacktrace will be able to tell you what line of code is causing the crash.
Use finally block in your code which is like
`try{
} catch{
} finally{
}`
finally will execute even if your try block throws exception or even if it doesn't.