Naveen Verma
Naveen Verma

Reputation: 50

Try catch (IOException g) Error

I get the error exception java.io.IOException is never thrown in body of corresponding try statement if I try to catch an IOException. But if I use Exception instead, the error is gone. Can someone describe why this happens?

public class CmndLine {
    public static void main(String args[]) {
        int i, j = 0;
        long m, l;
        boolean b1 = false;
        String str = "";
        String [] s;

        for (i = 0; i < args.length; i++)
            str += args[i];

        File file = new File(str);

        try {
            b1 = file.exists();
            System.out.println(b1);

            if (b1 == true) {
                m = file.lastModified();
                l = file.length();
                s = file.list();
                java.util.Date d = new java.util.Date(m);
                System.out.println("Name : " + file.getName());
                System.out.println("Parent : " + file.getParent());
                System.out.println("Path : " + file.getPath());
                System.out.println("Date and Time of Modification : " + d);
                System.out.println("Size : " + l + " Bytes");
                boolean c = file.isDirectory();

                if (c == true) {
                    System.out.println("");
                    for (String t : s)       
                        System.out.println(t);
                }
            }
        }
        catch (IOException g) {
            g.printStackTrace();
        }
    }
}

Upvotes: 0

Views: 280

Answers (2)

Tom
Tom

Reputation: 17597

There is no command in your try block that could throw an IOException. Therefore you will never catch one and your IDE/Compiler is telling you that.

If you write catch(Exception e) instead, you'll catch any possible Exception, like the SecurityException that methods like File.exists(), File.lastModified() and File.length() can throw.

So, try to use catch(SecurityException e) instead and add additional catch blocks for any specific Exception type you want to catch.

Upvotes: 0

Robby Cornelissen
Robby Cornelissen

Reputation: 97351

None of the methods you are using in your try block declare that they throw checked exceptions of type IOException, therefore you cannot catch it.

Since Exception encompasses both checked and unchecked exceptions, it doesn't give you the same problem.

Upvotes: 1

Related Questions