Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch block variable warning in Java

Tags:

java

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.

like image 494
Sheridan Avatar asked Aug 31 '11 14:08

Sheridan


People also ask

Can we handle error in catch block?

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.

What happens if exception occurs in catch block in Java?

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.

Can we override catch block in Java?

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.

Can we throw exception in catch block?

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.


2 Answers

Log the exception. It is always useful anyway when chasing a bug.

like image 191
cadrian Avatar answered Nov 08 '22 19:11

cadrian


Use the @SuppressWarnings("unused") annotation.

See also:

  • Annotations tutorial
  • Supported Values for @SuppressWarnings
like image 39
mre Avatar answered Nov 08 '22 21:11

mre