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.
Related
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.");
}
I'm new to coding, and very new to java, so please bear with me, I'm sorry.
My professor says we need to use the following code as part of our assignment. I've looked through all my notes for the class, and I cannot find anything on try-catch and I'm not sure what I'm supposed to put in the insert code part or what the error message means
I'm very sorry, I'm just very confused. I keep getting
"Unreachable catch block for FileNotFoundException. This exception is never thrown from the try statement body"
and I don't know how to fix it
try
{
File file = new File( args [ 0 ] );
Scanner scanner = new Scanner( file );
//insert code
scanner.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
Edit: I didn't get that error again after fixing it until I tried hard-coding a text file to test things out.
try
{
File file = new File( args [ 0 ] );
Scanner scanner = new Scanner("cat.txt");
//insert code
scanner.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
I am once again getting "Unreachable catch block for FileNotFoundException. This exception is never thrown from the try statement body"
What am I supposed to put in the try statement? I am so lost
I didn't get that error again after fixing it until I tried hard-coding a text file to test things out.
try
{
File file = new File( args [ 0 ] );
Scanner scanner = new Scanner("cat.txt");
//insert code
scanner.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
I am once again getting "Unreachable catch block for FileNotFoundException.
new Scanner(String) is not the same as new Scanner(File). If you look at the documentation, the first (using a String) reads from the string, not from a file. Since no file is involved, there's no FileNotFoundException.
If you want to hardcode the filename for testing purposes, do that in the new File(...) line, not the new Scanner(...) line:
try
{
File file = new File("cat.txt"); // <==== Here
Scanner scanner = new Scanner(file);
//insert code
scanner.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
That will compile, because new Scanner(File) throws FileNotFoundException.
Welcome to SO! Exceptions are a great way to catch errors and decide how to handle them. Some segments of code require the program to take a leap and attempt to perform a task that may not be possible at that moment.
The errors specified in the question are a result of the Scanner not finding the file at the specified file path. The ArrayIndexOutOfBounds is indicating exactly what the exception states. The index being accessed is outside the bounds(size) of the array.
Java docs is a great resource and this should help clarify the purpose of catch statements.
https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
Good day,
Why in video lessons one human was not using try-catch, and, if i not be using try-catch i have an error IOException on createnewFile(), FileWriter etc.
Maybe this is easy, i from c++, its big question for me.
Thats my code:
PS. Sorry for "best english"
public static void main(String[] args) {
System.out.println("Hello World");
File file1 = new File("temp.txt");
if(!file1.exists()) {
System.out.println("Creating file...");
try
{
file1.createNewFile();
}
catch (IOException e)
{
e.printStackTrace();
}
}
try
{
FileWriter fw = new FileWriter(file1);
BufferedWriter out = new BufferedWriter(fw);
out.write("aString");
out.flush();
out.close();
FileReader fr = new FileReader(file1);
BufferedReader in = new BufferedReader(fr);
while(in.ready()) {
System.out.println(in.readLine());
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
We use try- catch block to maintain the flow of execution of code.
If exception occurs it goes to catch block and e.printStackTrace it gives us the information why exception occurs and we can handle it here with our logic.
if we dont use try-catch the flow of code is stuck where exception occurs.
So thats why we use try-catch block.
Java requires that you handle checked exceptions in your code, either by specifying that your method can throw the exception or by handling it with a try-catch block. If you don't do one of these two at the point where you call a method that may throw a checked exception such as IOException, the compiler is going to produce an error.
You can learn about exceptions in Java here: Lesson: Exceptions (Oracle Java Tutorials).
Specifically: The Catch or Specify Requirement
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.
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.