Skip to content
Advertisement

Not Permitted to Use File Not Found Exception, but it is necessary

so I am having a strange problem where I am trying to use a try-catch, but the exception it not permitting. I will try to be as clear as I can describing the issue.

Some background: Okay, so the assignment is to basically allow the user to write some files and also read them. And so I’m at the part in my code where I am calling a previously made file. The user gets to type in the file that they wish to call, and so of course this exception is mandatory. But the error says that the exception is never thrown, but when I run the code it does get thrown. Let me show you some code.

JavaScript

Okay so this is my written code. Now here is my output (running without a try-catch)

This is my output without using a try-catch

And this is my error:

Exception in thread “main” java.lang.Error: Unresolved compilation problem: Unreachable catch block for FileNotFoundException. This exception is never thrown from the try statement body

at fileLab2.MemoMaker.main(MemoMaker.java:126)

Hopefully somebody can help with this problem. I made this account just for this question, honestly, it’s pretty annoying. Please ask if you need any clarification.

Here is my entire program:

JavaScript

Advertisement

Answer

This line,

JavaScript

even if, like you can see below written in the JavaDoc, will not throw any exception should preferrably (but that is not mandatory) be contained within your try...catch and using a FileInputStream (which should be contained inside the try block) because it is the new FileInputStream() constructor which is throwing an exception. Remove the use of Scanner also when trying to read a file efficiently.

Here is a useful link :


Javadoc

public File(String pathname) Creates a new File instance by converting the given pathname string into an abstract pathname. If the given string is the empty string, then the result is the empty abstract pathname.

That means that it does not check if the file exists or not.


Solution

JavaScript
Advertisement