How to "catch" this?

P

Prabh

Hello all,
I'm trying to access and describe a file and print out some messaging
if the file's not found.
Can anyone tell me what I'm doing wrong with try/catch?
I run into : "
exception java.io.FileNotFoundException is never thrown in body of
corresponding try statement
catch ( FileNotFoundException fne ) {
^

Should I throw my own exception?

===================================================================================
import java.io.* ;

public class findFile {
public static void main ( String args[] ) {
try {
File file = new File("myFile.txt") ;
long getLength = file.length() ;
System.out.println("Length is: " + getLength ) ;
}

catch ( FileNotFoundException fne ) {
System.out.println("Cant Access file!!") ;
fne.printStackTrace() ;
}

}
}
===================================================================================

I tried removing the try/catch, but it gives a misleading answer when
the file's not found, "Length is: 0".
I know, "0" mostly means a non-existent file, but I want put it in
plain English for the user.
I have to catch this thing.

Thanks for any pointers,
Prabh
 
S

Sergio Juan

Hi.

It just means what it says... inside the try block none of the methods you
call is defined to throw that exception (check the API; the constructor does
not and getLength() won't, probably). Try to catch an exception that is
defined.
ITOH, it does exist the method "exists()" in java.io.File that just checks
for the existence of the file.

Regards.
 
S

Steven Coco

Sergio said:
Hi.

It just means what it says... inside the try block none of the methods you
call is defined to throw that exception (check the API; the constructor does
not and getLength() won't, probably). Try to catch an exception that is
defined.
ITOH, it does exist the method "exists()" in java.io.File that just checks
for the existence of the file.

Indeed. Use file.exists() to determine if the file exists.

--

..Steven Coco.
.........................................................................
When you're not sure:
"Confess your heart" says the Lord, "and you'll be freed."
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top