0

I'm writing a program to practice throwing exceptions, and get compile error in one of the test:

MyTest.java:29: error: unreported exception FileNotFoundException; must be caught or declared to be thrown:

Assert.assertEquals("File Not Found", task2.fileNotFoundExTest());

^

public void fileNotFoundEx() throws FileNotFoundException {
        File fileName = new File("foo.txt");
        BufferedReader rd = new BufferedReader(new FileReader(fileName));
    }

public String fileNotFoundExTest() throws FileNotFoundException {
        try {
            fileNotFoundEx();
        } catch (FileNotFoundException e) {
            return "File Not Found";
        }
        return "No Error";
    }

I don't know why this error occurs because I already put the method that causes exception in a try-catch block and add signature "throws FileNotFoundException" to both methods. Can anyone explain this?

thu.vix
  • 43
  • 6

1 Answers1

1

You have declared that the method throws an exception - which it doesn't:

public String fileNotFoundExTest() throws FileNotFoundException {

Just change to:

public String fileNotFoundExTest() {
DuncG
  • 12,137
  • 2
  • 21
  • 33