Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

unreported exception despite of try-catch block

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());

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

^

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?

>Solution :

You have declared that the method throws an exception – which it doesn’t:

public String fileNotFoundExTest() throws FileNotFoundException {

Just change to:

public String fileNotFoundExTest() {
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading