'BufferedWriter without try method IOException
I know this topic has been discussed a lot and I have already read a lot of posts here about that, but I still seem to have trouble.
My problem is that I am also a beginner and I don't really understand how ĸwork and the try and catch function.
I have been trying to write to a file some string array, but it doesn't appear in there, nor the catch error is displayed in the console. I don't want to use the try method in this case, because when I am, I cannot use the variable declared for let's say BufferedWriter in other places, I am only restricted to the try method. Otherwise, I get a bug.
This is my code:
import java.io.*;
import java.util.*;
import java.lang.*;
public class FileWrit {
public static void main (String[] args){
try(BufferedWriter writer = new BufferedWriter(new FileWriter("testing.txt"))) {
String[] anything = new String[3];
writer.write("anything");
anything[0] = "case1";
anything[1] = "This is 1.5";
anything[2] = "Case 3, i do not know how to count";
for(String mem: anything) {
writer.append(mem);
}
writer.close();
} catch(IOException e) {
System.err.println("Idk when should this appear?");
}
}
}
Solution 1:[1]
For the "can't use it anywhere" part of your problem, you could declare the variable outside of the try catch block and only assign it inside. You can do a null check wherever else you want to use it to make sure there's no problems, or assign it another value in the catch block. Like so:
public static void main(String[] args) {
BufferedWriter writer;
String[] anything;
try {
writer = new BufferedWriter(new FileWriter("testing.txt"))) {
anything = new String[3];
writer.write("anything");
anything[0] = "case1";
anything[1] = "This is 1.5";
anything[2] = "Case 3, i do not know how to count";
for (String mem: anything) {
writer.append(mem);
}
writer.close();
} catch (IOException e) {
writer = null;
e.printstacktrace();
}
}
}
if(writer != null){
System.out.println(writer);
}
Solution 2:[2]
try and catch it's use for managed the exception. try this code:
import java.io.*;
import java.util.*;
import java.lang.*;
public class FileWrit {
public static void main (String[] args){
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("testing.txt"))
String[] anything = new String[3];
writer.write("anything");
anything[0] = "case1";
anything[1] = "This is 1.5";
anything[2] = "Case 3, i do not know how to count";
for(String mem: anything) {
writer.append(mem);
}
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
The System.err.println("Idk when should this appear?"); appear when you have an Exception in your try "an Error".
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Louis |