You can't put reader.close() between the try and the catch. Either put it in a finally block, or use a try-with-resources. Like,
try (BufferedReader reader = new BufferedReader(new FileReader(filenameIn))) {
reader.readLine();
for (int i = 0; i < personArray.length; i++) {
String[] data = reader.readLine().split("/t"); // <-- should be \\t for tab.
personArray[i] = new Person(Integer.parseInt(data[0]), data[1],
data[2], Integer.parseInt(data[3]));
}
} catch (IOException e) {
System.out.println("ERROR: WRONG FILE " + e.toString());
} catch (Exception e) {
System.out.println("ERROR" + e.toString());
}
or with the finally block,
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(filenameIn));
reader.readLine();
for (int i = 0; i < personArray.length; i++) {
String[] data = reader.readLine().split("\\t"); // <-- to split on tab.
personArray[i] = new Person(Integer.parseInt(data[0]),
data[1], data[2], Integer.parseInt(data[3]));
}
} catch (IOException e) {
System.out.println("ERROR: WRONG FILE " + e.toString());
} catch (Exception e) {
System.out.println("ERROR" + e.toString());
} finally {
if (reader != null) {
reader.close();
}
}
Answer from Elliott Frisch on Stack OverflowI keep receiving this error: 'try' without 'catch', 'finally' or resource declarations. I’ve tried to add and remove curly brackets, add final blocks, and catch blocks and nothing is working.
https://codepen.io/angelineb/pen/KKQpbqV
Videos
You can't put reader.close() between the try and the catch. Either put it in a finally block, or use a try-with-resources. Like,
try (BufferedReader reader = new BufferedReader(new FileReader(filenameIn))) {
reader.readLine();
for (int i = 0; i < personArray.length; i++) {
String[] data = reader.readLine().split("/t"); // <-- should be \\t for tab.
personArray[i] = new Person(Integer.parseInt(data[0]), data[1],
data[2], Integer.parseInt(data[3]));
}
} catch (IOException e) {
System.out.println("ERROR: WRONG FILE " + e.toString());
} catch (Exception e) {
System.out.println("ERROR" + e.toString());
}
or with the finally block,
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(filenameIn));
reader.readLine();
for (int i = 0; i < personArray.length; i++) {
String[] data = reader.readLine().split("\\t"); // <-- to split on tab.
personArray[i] = new Person(Integer.parseInt(data[0]),
data[1], data[2], Integer.parseInt(data[3]));
}
} catch (IOException e) {
System.out.println("ERROR: WRONG FILE " + e.toString());
} catch (Exception e) {
System.out.println("ERROR" + e.toString());
} finally {
if (reader != null) {
reader.close();
}
}
You can also eliminate the reader.close() call altogether by using try-with-resources.
try (FileReader fr = new FileReader(filenameIn)) { ... }
It depends on whether you can deal with the exceptions that can be raised at this point or not.
If you can handle the exceptions locally you should, and it is better to handle the error as close to where it is raised as possible.
If you can't handle them locally then just having a try / finally block is perfectly reasonable - assuming there's some code you need to execute regardless of whether the method succeeded or not. For example (from Neil's comment), opening a stream and then passing that stream to an inner method to be loaded is an excellent example of when you'd need try { } finally { }, using the finally clause to ensure that the stream is closed regardless of the success or failure of the read.
However, you will still need an exception handler somewhere in your code - unless you want your application to crash completely of course. It depends on the architecture of your application exactly where that handler is.
The finally block is used for code that must always run, whether an error condition (exception) occurred or not.
The code in the finally block is run after the try block completes and, if a caught exception occurred, after the corresponding catch block completes. It is always run, even if an uncaught exception occurred in the try or catch block.
The finally block is typically used for closing files, network connections, etc. that were opened in the try block. The reason is that the file or network connection must be closed, whether the operation using that file or network connection succeeded or whether it failed.
Care should be taken in the finally block to ensure that it does not itself throw an exception. For example, be doubly sure to check all variables for null, etc.
As explained above this is a feature in Java 7 and beyond. try with resources allows to skip writing the finally and closes all the resources being used in try-block itself. As stated in Docs
Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
See this code example
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
In this example the resource is BufferReader object as the class implements the interface java.lang.AutoCloseable and it will be closed whether the try block executes successfully or not which means that you won't have to write br.close() explicitly.
Another important thing to notice here is that if you are writing the finally block yourself and both your try and finally block throw exception then the exception from try block is supressed.
While on the other hand if you are using try-with-resources statement and exception is thrown by both try block and try-with-resources statement then in this case the exception from try-with-resources statement is suppressed.
As the @Aaron has answered already above I just tried to explain you. Hope it helps.
Source: http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
This is a new feature in Java 7 and beyond. Without this, you'd need a finally block which closes the resource PrintWriter out. So the code above is equivalent to:
PrintWriter out = null;
try {
PrintWriter out = ...
} finally {
if(null != out) {
try {
out.close();
} catch(Exception e) {} // silently ignore!
}
}
See The try-with-resources Statement
I have used try/catch when programming, and I've seen people use try/catch/finally.
According to my research, the `finally` part always executes, regardless of whether an exception was caught.
What is the purpose of that? Can't I just put the `finally` stuff after the `try/catch` stuff instead of making an extra block of code?
Hi and sorry for the noob question,
I am calling another python script as a subprocess. The python script tries to do X, and if/when it fails it MUST do Y. I had originally been handling this by doing the following:
try:
x
except:
<code to be run>For what I want to do, would it be better to simply use:
try:
x
finally:
yIf I understand correctly, I am basically using except for something finally should be used for at the moment, yes? Is there any downside to not using except for what I want to accomplish?
Maybe I’m just too early in learning Java to understand the reason you’d use it and for my purposes it’s irrelevant, but I’m curious.
I know it executes regardless of whether an exception is caught but doesn’t the code below a try {} catch {} block also execute regardless of whether an exception is caught? Isn’t that PART of the point of catching the exception? For the code to continue?
Forgive my ignorance, as there may be some serious misunderstandings of concepts in this post.
Thank you.
try {
//Code throwing exeption
} catch(Exception e) {
System.debug('An exception occurred: ' + e.getMessage());
} finally {
// Why here
}
//And not here
Okay, so I am very familiar with try and except (or catch in c# I guess), but the one I am not sure about is the finally keyword used like:
finally
{
Console.WriteLine("This worked anyway");
}
I understand that this is supposed to run regardless if the Try or Except worked, but the question I have (and also sort of the problem I have with this) is whatever you are doing in this, couldn't you also just do outside of the try/catch block of code? I'm not entirely sure why this is necessary in C# (or in any language). Can someone please explain why we need this.