Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to catch an exception that is "never thrown" in Java

I have the following block of code, which uses the JSCH library found at http://www.jcraft.com/jsch/

try {
    channel.put(f, filename);
} catch (FileNotFoundException e) {
    System.out.println("no file.");
}

I know that the put method can throw a FileNotFoundException when the file specified by f is not found locally, but eclipse tells me that the catch block is unreachable, and that exception can never be thrown. When I change to:

try {
    channel.put(f, filename);
} catch (Exception e) {
    System.out.println(e.getMessage());
}

I get:

java.io.FileNotFoundException: C:\yo\hello2 (The system cannot find the file specified)

Any ideas?

like image 579
ewok Avatar asked Sep 06 '11 16:09

ewok


People also ask

Can we catch exception without throw?

You can avoid catching an exception, but if there is an exception thrown and you don't catch it your program will cease execution (crash). There is no way to ignore an exception. If your app doesn't need to do anything in response to a given exception, then you would simply catch it, and then do nothing.

What happens if you don't throw an exception Java?

If the programmer did not declare that the method (might) throw an exception (or if Java did not have the ability to declare it), the compiler could not know and it would be up to the future user of the method to know about, catch and handle any exceptions the method might throw.

What happens when an exception is never caught?

What happens if an exception is not caught? If an exception is not caught (with a catch block), the runtime system will abort the program (i.e. crash) and an exception message will print to the console.

Can we catch without try?

Yes, It is possible to have a try block without a catch block by using a final block. As we know, a final block will always execute even there is an exception occurred in a try block, except System. exit() it will execute always.


2 Answers

I think your FileNotFoundException is wrapped in another thrown by the channel method and therefor you cannot catch it.

Try printing the class of the exception thrown by the method:

...
} catch (Exception e) {
   System.out.println(e.getClass());
}
like image 167
dacwe Avatar answered Sep 17 '22 07:09

dacwe


Check your import statements to ensure you are not importing a FileNotFoundException class from a package besides java.io.

like image 45
cheeken Avatar answered Sep 20 '22 07:09

cheeken