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
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 guess that's the reason why...
- 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.
Hope this helps.
I think you might have compiled the program like this
dirmkdir() doesn't throws any exception and more over you can not use checked exception for try catch if not the corresponding code /doesn't throws checked exception.
[Devaka: Added code tags - Please UseCodeTags]