Home > Blockchain >  unreported exception despite of try-catch block
unreported exception despite of try-catch block

Time:11-13

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?

CodePudding user response:

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

public String fileNotFoundExTest() throws FileNotFoundException {

Just change to:

public String fileNotFoundExTest() {
  • Related