Getting FileNotFoundException even though I declared it to be thrown - java

I am currently writing a Text Editor using linked lists, and I am pretty much done but I come across a FileNotFoundException when trying to test my program's command line, even though I declared it to be thrown.
Here is the skeleton for my Editor:
public class Editor {
public Editor() {
}
public void commandLine() throws FileNotFoundException {
}
}
Here is the driver for my program:
public class EditorTest
{
public static void main(String[] args)
{
Editor asdf = new Editor();
asdf.commandLine();
}
}
I am still getting an error for an unreported FileNotFoundException even though I declared it to be thrown in my command line method. What is wrong?

You need to add throws FileNotFoundException to your main method. Or, you can add:
try {
asdf.commandLine();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
to your main method, depending on what you need to do based on that exception.

Yo need to declare it on main, too
public static void main(String[] args) throws FileNotFoundException {

Declaring an Exception to be thrown in a method (i. e. using throws MyException) doesn't prevent the exception to be thrown, it rather allows the method to throw it for a caller of that method to have to catch that Exception

Related

Usage of throws and try-catch in the same method [duplicate]

This question already has an answer here:
What does "error: unreported exception <XXX>; must be caught or declared to be thrown" mean and how do I fix it?
(1 answer)
Closed 6 months ago.
Can we use throws and try-catch in the same method?
public class Main
{
static void t() throws IllegalAccessException {
try{
throw new IllegalAccessException("demo");
} catch (IllegalAccessException e){
System.out.println(e);
}
}
public static void main(String[] args){
t();
System.out.println("hello");
}
}
The error displayed is
Main.java:21: error: unreported exception IllegalAccessException; must be caught or declared to be thrown
t();
^
1 error
So I thought of modifying the code and I added an another throws statement to main() method and the rest is same.
public class Main
{static void t() throws IllegalAccessException {
try{
throw new IllegalAccessException("demo");
} catch (IllegalAccessException e){
System.out.println(e);
}
}
public static void main(String[] args) throws IllegalAccessException{
t();
System.out.println("hello");
}
}
But now I'm getting the desired output.
But I have some questions...
Can we use throws and try-catch in single method?
In my case is it necessary to add two throws statement , if not tell me the appropriate place to add?
In your code
void t() throws IllegalAccessException
you are telling the compiler that this code throws an exception (whether it does or not is another matter), and so any method calling this method either has to catch it or declare that it also throws it etc. etc.
As you are not actually throwing an exception from t you can remove the declaration.
void t()

Using throws keyword and handling it in the main rather than handling it in the method in which it occurs

If I add the throws keyword in the method signature and handle it in my main() inside my TestClass{}, is it a good approach or should I handle the exception in the method in which it occurs fooBar(), which approach is recommended or what are the trade-offs between the two. Sorry this question might seem a little weird, just a newbie in Java.
public class Foo {
//private fields
public Foo() {
//ctor
}
//accessors and mutators
//method that throws exception
public void fooBar() throws FooBarException {
throw new FooBarException();
}
}
Generally, the scope of try block should be as small as possible.
public void fooBar(){
try{
//Lines that can through error
}
catch (FileNotFoundException e) {
//Handle exception Here
//e.printStackTrace();
/*
other code that will not throw any error
*/
}
or if the whole block may throw the error then
public void fooBar() throws FooBarException {
}
//Handle in the exception where you calling the method

Accessing field in super to report error

I'm not great with java terminology so it will be easier for you to understand via example:
I instantiate a mymethods class from a
Main class:
public class Main()
{
public boolean hasErrors = false;
MyMethods m = new MyMethods(); //cannot use try/catch
public static void main(String[] args){
m.writeToFile("text");
}
}
In the above class, i cannot (i tried) use a try catch to catch a manually thrown FileNotFoundException but apparently such methods cannot be used in that location (wrapping MyMethods m... in try/catch). I had tried to throw that error when my requisite file wasnt found
MyMethods:
public class MyMethods()
{
public MyMethods(){
if(!new File("file.txt").canWrite()){
changeSuper(true);
throw new FileNotFoundException();
}
}
public void changeSuper(boolean b) //does not work
{
super.hasErrors = b;
}
//input more methods etc here
}
Why is it not possible to use try/catch?
How can i report a filenotfound to the main method?
Note that this is from a GUI app in netbeans, but is not the focus here. Program will not compile if try/catch wraps that line
(note to admins/mods: this question needs butchering, but I cannot express my question better myself)
You just need to add the throws keyword to your method, i.e:
public static void myMethod() throws FileNotFoundException{
// Code goes here ...
if( fileNotFound )
throw new FileNotFoundException("File not found.");
}
you can then catch the exception by surrounding your call to the method with a try/catch block:
try {
// Do stuff...
myMethod();
} catch (FileNotFoundException ex){
// Handle error, if thrown...
}

Execute performExecute() using public static main(String args)

public class XGetProgramGuideDirectTestControllerCmdImpl extends ControllerCommandImpl implements XGetProgramGuideDirectTestControllerCmd {
public final String CLASSNAME = this.getClass().getName();
public void performExecute() throws ECException { /* code is here*/ }
private void callUSInterface() throws ECException { /* code is here*/ }
private void callDEInterface() throws ECException { /* code is here*/ }
private void callUKInterface() throws ECException { /* code is here*/ }
public void setRequestProperties(TypedProperty req) throws ECException { /* code is here*/ }
private void displayResponse(StringBuffer testResult) { /* code is here*/ }
public static void main(String[] args) {
XGetProgramGuideDirectTestControllerCmdImpl PGDirTestController = new XGetProgramGuideDirectTestControllerCmdImpl();
PGDirTestController.performExecute();
}
}
I'm simply trying to run this application as a java application in Eclipse-RAD using public static void main(String[] args) but it is giving me an error of:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type ECException
on:
PGDirTestController.performExecute();
Please go easy on me, I'm pretty new to Java still.
Since you declared:
public void performExecute() throws ECException
Then you are forced to deal with ECException.
So when you call it, you should surround it with try-catch or declare the method in which you call it to throw the exception:
public static void main(String[] args) {
XGetProgramGuideDirectTestControllerCmdImpl PGDirTestController = new
XGetProgramGuideDirectTestControllerCmdImpl();
try {
PGDirTestController.performExecute();
} catch(ECException e) {
e.printStackTrace();
//Handle the exception!
}
}
OR
public static void main(String[] args) throws ECException {
XGetProgramGuideDirectTestControllerCmdImpl PGDirTestController = new
XGetProgramGuideDirectTestControllerCmdImpl();
PGDirTestController.performExecute();
}
First, variables should start with lowercase as per Java convention, otherwise it's confusing:
XGetProgramGuideDirectTestControllerCmdImpl pGDirTestController = new XGetProgramGuideDirectTestControllerCmdImpl();
About your question, Unhandled exception type means this method throws an exception that's not a RuntimeException and you're not handling it. In Java, you must explicitly catch all exceptions that are not children of RuntimeException.
try {
pGDirTestController.performExecute();
} catch (final ECException e) {
// Do whatever you need to do if this exception is thrown
}
The catch part will be executed whenever an ECException is thrown. You should add code here to handle what to do if this exception is thrown. I strongly advise you against leaving this catch empty, because if the exception is thrown, you'll never know.
I strongly suggest you get a Java book/tutorial if you will be working with Java. This is very basic stuff, so you better understand this very well. Good luck.

Java Code without Try and Catch

I have the code:
public class RssReader {
private File dataFile = new File("data.dat");
private FileInputStream dataStream = new FileInputStream("data.dat");
boolean fileExists;
public static void main(String[] args) {
}
}
My question is, can I put FileInputStream or any code that requires Try/catch as a global function?
Yes you can. you can declare that main method throws an Exception of any kind, i.e.
public static void main(String[] args) throws IOException {
}
And you can omit the try-catch block in the code.
I would highly suggest NOT doing that, though. First of all, try-catch blocks exist for a reason. They are here to catch exceptions that you might foresee but have no control of (i.e. bad file format). Second of all, they will let you close the streams in finally blocks even if the exception happens.
Yes you can if you let your constructor throws the exception :
class RssReader {
private File dataFile = new File("data.dat");
private FileInputStream dataStream = new FileInputStream("data.dat");
boolean fileExists;
RssReader()throws IOException{}
}
Then each time you will construct a new RssReader object, the method that handle this construction should throws it too (like darijan said), or you can create a try-catch block in this method :
public void someMethod() throws IOException {
RssReader r = new RssReader();
}
or :
public void someMethod() {
RssReader r;
try {
r = new RssReader();
} catch (IOException e) {
e.printStackTrace();
}
}
You may add that code by signing the method with throws Exception. But it is not recommended when you have an stream reader or something like that because often you gotta close the stream or flush the writers.
I think you should think about it when you need to open or close a stream object.
There are several things you can do and several you can't:
You can't initialize a variable with code that can throw a checked exception. The compiler will complain. So your line beginning private FileInputStream ... is illegal.
You can't use the instance variables inside the static main() method. The compiler will again complain once you put ... dataStream ... inside main().
You can put a throws IOException on the main method.
One way to deal with these things is to do this:
public class RssReader {
public static void main(String[] args) throws IOException {
File dataFile = new File("data.dat");
FileInputStream dataStream = new FileInputStream("data.dat");
boolean fileExists;
... use the variables here ...
}
}
which will toss you out to the command line if you run the program and, for example, the file doesn't exist. An error message and stack trace will be printed if that happens.
What I did up there is move all the variables into the scope of the main() method. Then I added the throws on the method so it will let whatever basic part of Java calls main() handle the exception.
Or you could do something another way like this:
public class RssReader {
private static File dataFile = new File("data.dat");
private static FileInputStream dataStream;
static {
try {
dataStream = new FileInputStream("data.dat");
} catch (IOException e) {
throw new RuntimeException(e); // this isn't a best practice
}
}
static boolean fileExists;
public static void main(String[] args) {
... use the variables here ...
}
}
which will do the same thing if there is a problem with finding the file. Out to the command line and print messages.
This hides the possible checked exception inside a static initializer block with a try-catch around it. The checked exception is turned into an unchecked exception. It also makes all the variable static so they can be used in the static method main()
One more possible solution that's an even better way:
public class RssReader {
private File dataFile = new File("data.dat");
private FileInputStream dataStream;
boolean fileExists;
public RssReader() throws IOException {
dataStream = new FileInputStream("data.dat");
}
public void doTheWork() {
... use all the variables here ...
}
public static void main(String[] args) {
try {
reader = new RssReader();
reader.doTheWork();
} catch (IOException e) {
System.out.printf("File 'data.dat' not found. Exiting ...");
}
}
}
which is the one I like best. It gives you control over what happens if an exception happens so we print an informative message and tell them the program is finished. All the variables are instance variables inside the object instance created in the main() method. Main does almost nothing but create the instance and tell it to get to work. Main also decides what to do if it fails.
The changes are to move everything to instance scope and out of static scope, except catching the fatal exception. You can leave your variables at the top where they are easy to read. The method that does the work is given a name to describe what it does.

Categories