Clarification required against this piece of code in Java
-
28-09-2019 - |
Question
when I write this piece of
String path="d:\\test.txt";
boolean chk;
File f=new File(path);
try
{
chk=f.createNewFile();
}catch(IOException e)
{
chk=false;
e.printStackTrace();
}
if(chk)
System.out.println("file created.");
else
System.out.println("file not created");
file is created in d-drive
but when I use this
String path="d:\\test.txt";
File f=new File(path);
if(f.createNewFile())
System.out.println("file created.");
else
System.out.println("file not created");
it throws exception.
Please enlighten me on this
Solution
Change second part of you code to following:
String path = "d:\\test.txt";
File f = new File(path);
try {
if (f.createNewFile())
System.out.println("file created.");
else
System.out.println("file not created");
} catch (IOException e1) {
e1.printStackTrace();
}
You are required to do this because if you don't surrond f.createNewFile() within try/catch block, your code won't compile. As usage of f.createNewFile() throws IOException you need to either put it in try/catch block catching IOException or method using this part of code needs to declare throws IOException.
OTHER TIPS
I doubt that the second piece of code actually "throws an exception"; most likely what you are seeing is a compile error warning you that you must catch the checked exception IOException
when you call createNewFile
.
A "checked" exception must have a handler or be declared by the calling method via throws
, or your code will not compile. IOException
is checked. createNewFile
declares that it throws IOException
. Therefore your second block of code is not correct.
File.createNewFile() throws an exception if the file already exists (or you don't have the right to create the file). So after running the first piece of code... the second will fail, if you forgot to delete test.txt.
I guess you get an IO exception or you cannot create (write) that file, maybe because it's opened.