ewok
ewok

Reputation: 21493

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?

Upvotes: 8

Views: 3840

Answers (2)

dacwe
dacwe

Reputation: 43504

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());
}

Upvotes: 8

cheeken
cheeken

Reputation: 34675

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

Upvotes: 2

Related Questions