0

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(); } } } 
1
  • Could you give a full traceback? Commented Oct 30, 2014 at 10:35

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.