I try to get my code to compile with no errors and no warnings as standard practice. There is one annoying warning, though, that I know how to deal with in .NET but not in Java. Say I have a code block like this:
try {
FileInputStream in = new FileInputStream(filename);
return new Scanner(in).useDelimiter("\\A").next();
} catch (FileNotFoundException ex) {
LOG.log(Level.SEVERE, "Unable to load file: {0}", filename);
return null;
}
I get a warning that variable ex
is not used. Now, I don't really have a use for ex
, I don't want ex
, but I don't know what to do about it. In .NET I could just do:
catch (FileNotFoundException)
without the variable and it will compile and run with no error.
How would one handle this situation in Java? I know I could make a local variable and set it to ex
, but that seems like a silly and wasteful workaround to fix a warning that isn't really needed.
Yes, we can catch an error. The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the throw statement.
Answer: When an exception is thrown in the catch block, then the program will stop the execution. In case the program has to continue, then there has to be a separate try-catch block to handle the exception raised in the catch block.
Having try-catch in both places is pointless. The only way to execute the content in the both catch blocks is to re-throw the exception.
When an exception is cached in a catch block, you can re-throw it using the throw keyword (which is used to throw the exception objects). Or, wrap it within a new exception and throw it.
Log the exception. It is always useful anyway when chasing a bug.
Use the @SuppressWarnings("unused")
annotation.
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With