caught or declare might be thrown error
Code :
public class CreateFileMain{
public static void main(String[] args){
CreateFile object = new CreateFile();
object.openFile();
object.writeFile();
object.closeFile();
}
}
Code :
import java.io.*;
public class CreateFile{
BufferedWriter in;
public void openFile(){
try{
in = new BufferedWriter(new FileWriter("C:\\Users\\Hiep\\Desktop\\Java Programming\\file.text"));
System.out.println("shell, something is wrong");
}catch(Exception e){
}
}
public void writeFile(){
in.write("You did it");
}
public void closeFile(){
in.close();
}
}
any idea. I did some research but i still can't fix it.
Re: caught or declare might be thrown error
Code java:
public void openFile() {
try {
in = new BufferedWriter(new FileWriter("C:\\Users\\Hiep\\Desktop\\Java Programming\\file.text"));
System.out.println("shell, something is wrong");
} catch (IOException e) {
}
}
public void writeFile() {
try {
in.write("You did it");
} catch (IOException ex) {
}
}
public void closeFile() {
try {
in.close();
} catch (IOException ex) {
}
}
As all your methods do some sort of file handling, and the exceptions that could arise are checked exceptions, you're required to attempt to catch or throw a possible exception for all your methods.
Unless say openFile() called writeFile(), then you would only require one try...catch block to handle both.
On a side note, next time please try and structure your questions better, include more information about your problem and what you have tried yourself. The clearer the question the more help you will get.
Re: caught or declare might be thrown error
Code Java:
import java.io.*;
import java.lang.*;
import java.util.*;
public class CreateFile{
private Formatter in;
public void openFile(){
try{
in = new Formatter("C:\\Users\\Luke\\Desktop\\Java Programming\\file.text");
System.out.println("shell, something is wrong");
}catch(Exception e){
}
}
public void writeFile(){
in.format("%s%s%s","test","test","test");
}
public void closeFile(){
in.close();
}
}
can you tell me why this does require the IOException in every method? also, i don't understand why in need this IOexception
Re: caught or declare might be thrown error
You must catch checked Exceptions that may be thrown - it is a way of error handling in the code should something fail along the way. The API's that you use will specify exceptions - if any - that a certain method/constructor will throw. If you do not catch an checked exception in a method, that method must be declared to throw said exception. In the above example, I would recommend you deal with the exception in the catch clause, otherwise if something does go wrong you will have no way of knowing.
Suggested reading: Lesson: Exceptions.