If the file userguide.txt does not exist, what is the result?

Given the code fragment:

If the file userguide.txt does not exist, what is the result?

Given the code fragment:

If the file userguide.txt does not exist, what is the result?

A.
An empty file is created and success is printed.

B.
class java.io.FileNotFoundException.

C.
class java.io.IOException.

D.
class java.lang.Exception.

E.
Compilation fails.

Explanation:
Note:public FileReader(String fileName)
throws FileNotFoundException
Creates a new FileReader, given the name of the file to read from.

Parameters:
fileName – the name of the file to read from
Throws:
FileNotFoundException – if the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.

Reference:java.io Class FileReader



Leave a Reply 18

Your email address will not be published. Required fields are marked *


Boris

Boris

the correct answer is E.

Yury

Yury

Yes, there is compilation error because Derived process throws Exception.

ses

ses

Answer is B. compile it!!!

run:
class java.io.FileNotFoundException
BUILD SUCCESSFUL (total time: 3 seconds)

——————
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

class Base1{
public void process() throws IOException{
FileReader fr = new FileReader(“tmp.txt”);
BufferedReader br = new BufferedReader(fr);
String record;
while((record = br.readLine())!= null){
System.out.println(record);
}
}
}

public class Derived1 extends Base1{
public void process() throws IOException{
super.process();
System.out.println(“Sucess”);
}
public static void main(String[] args) {
try {
new Derived1().process();
} catch (Exception e) {
System.out.println(e.getClass());
}
}
}

Amol

Amol

In the question the Derived class process method throws Exception.
Your code compiles well and so the answer would be B

But with the actual code the answer is E

Robertinho

Robertinho

the correct answer is E.

error: process() in Test2 cannot override process() in Base1
public void process() throws Exception{
^
overridden method does not throw Exception

Ray

Ray

The answer is E.

process() in Derived cannot override process() in Base
overridden method does not throw Exception

GoodLuck

GoodLuck

E is correct.

Copied from Netbeans IDE
process() in Derived cannot override process() in Base
overridden method does not throw Exception

Rudi

Rudi

E is the correct answer.

While implementing a method, it is acceptable to either provide the throws clause listing the same exception type as the base method or a more specific type than the base method.