Generally whatever we write in the try block is actually tried to execute and if it causes some exception, then catch block comes to help but even if the try block does not throw exception, the compiler does not complain, but in my case, I want to create a directory and I am writing the code for that in try block but the compiler says something interesting as below
here is the code
and when program is compiled, then error is
F:\Java\Concepts\Strings,IO Formatting and Parsing\File IO>javac CreateFileAndDi
CreateFileAndDirectory.java:38: exception java.io.IOException is never thrown in
body of corresponding try statement
catch (IOException e)
but this does not happen in case of CreateFile() method, means it compiles fine but in case of CreateDirctury, it does not create, so I commented out the code for catch block
there is another example ,
here is simple code that compiles fine even if the try block does not throw any kind of exception
This compiler perfectly
what can be the difference?
I am finding it very very interesting
please help experts
SCJP 6 [86%], OCPWCD [84%], OCEJPAD [83%]
If you find any post useful, click the "plus one" sign on the right
Maybe it's because the method createNewFile() in File throws an IOException (it's not a RuntimeException (so, it must be catched), like ArithmeticException and NullPointerException, that only can be detected at runtime) and the mkdir() method doesn't throw that.
http://java.sun.com/javase/6/docs/api/java/lang/Exception.html wrote:The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.
http://java.sun.com/javase/6/docs/api/java/lang/RuntimeException.html wrote:A method is not required to declare in its throws clause any subclasses of RuntimeException that might be thrown during the execution of the method but not caught.
I am not sure if I completely understand your question, but let me try to give a shot at the answer:
- mkdir() doesn't throw an IOException. So you cannot have a catch block to catch an IOException for mkdir(). If you have one, the compiler will complain. Why the mkdir() doesn't throw an IOException is beyond me. I too would like to understand why it was designed that way.
- createNewFile() DOES throw an IOException. So you have to catch this Exception in a catch block (or declare that the method throws an IOException). Otherwise the compiler will complain.
- In your last example, you are catching an ArithmeticException which is a RuntimeException. In this case the code in the try block doesn't really have to throw a RuntimeException. You are free to catch any RuntimeException in a catch block, irrespective of whether your code in the try block throws one or not.