catch FileNotFoundException Java - java

I have this code, what it basically does is, it gets the string typed in a JTextPanel then assigns it to "conec". Then it creates a graph with the lines of that file.
The FileManagement.load_file(conec) method looks for the file with that name in the project folder and proceeds to run the code. Thing is, when I type the wrong name of file, I'm getting the FileNotFoundException, and I want it to say the "Invalid file", message but it's just not working it just keeps running the program.
This is what I have tried so far but not working, it gives the error and keeps running.
try {
String conec = archivo.getText();
Grafo g = FileManagement.load_file(conec);
cl = g.getClientes();
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(this, "Invalid File.");
}
JOptionPane.showMessageDialog(this, "File loaded correctly.");
}

After executing a catch block, the control automatically moves to statements following all the catch and finally blocks belonging to the try keyword.
What you can do (Any one of these):
java
catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(this, "Invalid File.");
e.printStackTrace();
java
catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(this, "Invalid File.");
System.exit(-1);
java
catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(this, "Invalid File.");
return;
java
catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(this, "Invalid File.");
throw new Exception(e);
java
catch (FileNotFoundException e) {
throw new Exception(e, "Invalid File.");

The 5 options of the other answer all work just fine, but there's an even more simple solution here in my opinion.
As a commenter pointed out, the message dialog that's supposed to open in the "correct" case will always open no matter if an Exception is thrown or not. I'm guessing you tried to simulate an else statement without actually writing the else which is possible:
if(somethingIsTrue)
{
doSomething();
}
doSomethingElse();
In this example, the method call to doSomethingElse() is an else statement despite never actually coding else. This behaviour is not replicated by a try/catch block. (If you never made this assumption and I'm just pulling stuff out of my ass ignore this part up to now),
I think the simplest fix, considering that the "correct" message should pop up when the try block executes succesfully, would be to simply add it to the try block:
try
{
String conec = archivo.getText();
Grafo g = FileManagement.load_file(conec);
cl = g.getClientes();
JOptionPane.showMessageDialog(this, "File loaded correctly.");
}
catch (FileNotFoundException e)
{
JOptionPane.showMessageDialog(this, "Invalid File.");
}

Related

EOFException with ObjectInputStream

I have read other questions similar to this but didn't help much. So I have some serialized content in a file and I am trying to read it and print it on the console, content is getting printed fine but at the end, it's showing an EOFException. Is there any way to fix my code to avoid this exception?
try {
File file = new File("EnrolledStudentsSerial.txt");
FileInputStream fi = new FileInputStream(file);
ObjectInputStream input = new ObjectInputStream(fi);
while(true) {
System.out.println(input.readObject());
}
}
catch (IOException | ClassNotFoundException e) {
System.out.println("Error: " + e);
}
I don't think you want to 'avoid' this exception.
You need to know when you come to the end of the input, and the EOFException is what is telling you you've come to the end of the input.
Rather, you want to stop treating it as an error condition, since it is not an error, it is normal and expected.
try {
… code as before …
}
catch (EOFException e) {
// end of input, nothing to do here
}
catch (IOException | ClassNotFoundException e) {
System.out.println("Error: " + e);
}

How to show an error message in java in a friendly way

I have a question as i am a beginner in java you may find it silly.
I am writing a method to read a file and when it does not exist an error just show up.
File f = new File(FILE_path);
if (f.exists() && f.canRead()) {
try {
//Do something
} catch (IOException e) {
e.printStackTrace();
LOGGER.error("Error message: " + e.getMessage());
}
} else {
LOGGER.error("File does not exist or it cannot be read.");
}
but other than the error that it shows the red error also shows up and then the program stops.
Exception in thread "main" java.io.FileNotFoundException: /home/project/file_path (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:146)
Now my question is that is there anyway that the program does not freeze at this level and we show only the friendly message? or we cannot avoid that and this Exception error always show up even we use try and catch?
you could always use joptionpanes:
File f = new File(FILE_path);
if (f.exists() && f.canRead()) {
try {
//Do something
} catch (IOException e) {
JOptionPane.showMessageDialog (null, "Something went Wrong", "Title", JOptionPane.ERROR_MESSAGE);
LOGGER.error("Error message: " + e.getMessage());
}
} else {
LOGGER.error("File does not exist or it cannot be read.");
}
is there anyway that the program does not freeze at this level and we show only the friendly message?
Yes. Your IDE (eclipse or whatever) probably automatically placed e.printStackTrace(); on the line after catch (IOException e) but you don't need to do this. And more experienced programmers would say it's completely unnecessary.
When you catch an exception in Java, you are getting control back after an Exception occurs. You can do absolutely anything after a catch that you can do at any other point in your program. You don't need to print the stack trace.
Sounds like you just want this:
`catch (IOException e) {
LOGGER.error("Error message: " + e.getMessage());
}
Edit if that is all you have in your catch block, then that is the only thing that will happen after an exception. Your program won't proceed out/down past the catch block.

Java catching exceptions and subclases

Hello,
In Java if a method like BufferedReader.read() says it can throw an IOException and I try to catch a FileNotFoundException and an IOException in two catch blocks, what catch blocks will be entered if the file doesn't exist?
Does it enter only the most specific or both?
The first coded catch that matches the exception will be entered.
Edited to incorporate comment from Azodius
For example:
try {
bufferedReader.read();
} catch (FileNotFoundException e) {
// FileNotFoundException handled here
} catch (IOException e) {
// Other IOExceptions handled here
}
This following code does not compile:
try {
bufferedReader.read();
} catch (IOException e) {
// All IOExceptions (and of course subclasses of IOException) handled here
} catch (FileNotFoundException e) {
// Would never enter this block, because FileNotFoundException is a IOException
}
Compiler message says:
Unreachable catch block for FileNotFoundException. It is already handled by the catch block for IOException
Only the first catch block encountered where the exception type of the catch block matches the type of the exception being thrown will be run (more specifically, the first catch block where (e instaceof <exception type>)==true will be run). None of the other catch blocks will be run.
For example
try{
BufferedReader.read();
}
catch(FileNotFoundException e){System.out.println("FileNotFoundException");}
catch(IOException e){System.out.println("IOException");}
Will print FileNotFoundException if BufferedReader.read() throws a FileNotFoundException.
Note that the following doesn't actually compile:
try{
BufferedReader.read();
}
catch(IOException e){System.out.println("IOException");}
catch(FileNotFoundException e){System.out.println("FileNotFoundException");}
because Java realizes that it is not possible for the FileNotFoundException to be caught because all FileNotFoundExceptions are also IOExceptions.
The first one which is suitable for that type of exception (and only that). So if you catch the two exception types above in the order you list them, a FileNotFoundException will be caught.
Specific exception is caught first. and it's a compile time error if generic exception is caught befor specific one.

JAVA + try catch(FileNotFoundException e) going in catch(Exception e)?

I have some command which creates a file on disk.
Because the folder in which the file has to be created is dynamic, I have a catch(FileNotFoundException e). In the same try block, I already have a catch(Exception e) block.
For some reason, when I run my code and the folder does not exists yet, the catch(Exception e) block is used, not the FileNotFoundException one.
The debugger is clear though (to me at least), showing a FileNotFoundException: java.io.FileNotFoundException: c:\mydata\2F8890C2-13B9-4D65-987D-5F447FF0DDA7\filename.png (The system cannot find the path specified)
Any idea why it doesn't go into the FileNotFoundException block?
Thanks;
CODE:
import java.io.FileNotFoundException;
try{
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRectangle = new Rectangle(screenSize);
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(screenRectangle);
ImageIO.write(image, "png", new File(fileName));
}
catch (FileNotFoundException e){
// do stuff here..
return false;
}
catch(Exception e){
// do stuff here..
return = false;
}
It's also possible that the specific issue you're having isn't a FileNotFoundException. By using the "Exception" in a catch block (which is the parent class to all Exceptions) this is effectively a "catch all", since it will run if there is an `Exception or any of its subclasses thrown.
Try the following change:
...
catch (Exception e) {
System.out.println(e.getClass());
}
...
This will tell you the specific class of the Exception being caught by this block. I'll bet you'll find that the Exception is actually an instance of a subclass (such as IOException, for example).
Your problem is that the FileNotFoundException is thrown somewhere deep inside the java library and not propagated up so you cannot catch it.
The real culprit here is a NullPointerException originating from the
ImageIO.write(image, "png", new File(fileName));
call. This one runs into your catch (Exception e) block.
If you add a catch (NullPointerException e) block before your general Exception catch, you will see it going in there.

try, catch and if error in a combo box with java and netbeans

I assure you all that this is not homework.
I have a combo box:
try {
double input = Double.valueOf(input1.getText());
double output = 0;
My combo box code here:
if (output < 2.50){
answerField.setText("£2.50");
}
else{
answerField.setText("£" + String.valueOf (fmt.format(output)));
catch (Exception e) { JOptionPane.showMessageDialog(this,
"Please enter numbers in the fields.
Numbers are 1 2 3 4 5 etc.",
"Oooops!!!",
JOptionPane.ERROR_MESSAGE);
}
The problem I have is that when I run it like this it won't work.
if I take the if statement out and leave try catch in, it works
and also if I take the try and catch out it and leave only the if, it also works
When I run it using the above, I get this error:
catch without try
; expected
Can anyone help?
you must close your else bracket, and then your try bracket:
try {
if (..) {
...
} else {
...
}
} catch (Exception e) {..}

Categories

Resources