user1916693
user1916693

Reputation: 125

What exception is thrown while creating a file in java

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Filewrite {
    public static void main(String args[]) {
        try{
            String content="This is my world";
            File f=new File("D:/abc.txt");
        }catch(IOException i) {
            i.printStackTrace();
        }
    }
}

Compilation of the above code gives an error:

IO exception is never thrown by this corresponding try block. 

What exception may be thrown while creating a file?

Upvotes: 0

Views: 3119

Answers (4)

Zohaib Munir
Zohaib Munir

Reputation: 1

Explanation

When ever you try to catch checked exception only which will never be thrown by your code in try block then compiler will always give you error of compilation. In this case you are not performing any file operation(creation, reading, writing). So your code will never throw any io exception which is checked exception. You can't catch that exception which will never be thrown by your try block.

How To Fix

You can fix by removing io-exception from catch block then code will compile fine.

Upvotes: 0

SSB
SSB

Reputation: 144

The error caused because your code block will never throw an IOException. IOException will be thrown mostly when doing IO operations on files or other sources

Upvotes: 0

SuRu
SuRu

Reputation: 739

IOException comes when

Signals that an I/O exception of some sort has occurred. This class is the general class of exceptions produced by failed or interrupted I/O operations.

in your code you are just creating a file object. It throws a NullPointerException if the path is null.

If you want to do any operations with that file like read, write etc... it throws FileNotFoundException and IOException

Upvotes: 0

Christian Tapia
Christian Tapia

Reputation: 34146

From Java Docs:

Throws:
NullPointerException - If the pathname argument is null

When you want to see what Exceptions are being thrown by a method (constructor in this case), you can search in Java Docs, or if you are using Eclipse IDE, put cursor over the method, and press F2.

Upvotes: 1

Related Questions