I have a Gui for a stopwatch, it has a Start button, a Stop button, and also a "Split" button, and a Save Splits button. The stopwatch records splits and I would like to be able to write them to a file but I have an error with:
FileWriter splitsWriter= new FileWriter("a.txt");
for(int i=0;i<theSplits.size();i++){
splitsWriter.write(theSplits.get(i));
}
It says Unhandled exception type IOException but I thought a writer creates the file if it doesn't exist so why should this exception be a problem? I'm just confused..
Like pstrjds already said you have to add a try/catch block. Your code should look like this:
try {
FileWriter splitsWriter= new FileWriter("a.txt");
for(int i=0;i<theSplits.size();i++){
splitsWriter.write(theSplits.get(i));
}
} catch (IOException e) {
// Do something to handle the exception
}
This should compile.
Related
public static void generateOutput() {
File file = new File ("C:/Users/me/Desktop/file.txt");
PrintWriter outputFile = null;
outputFile = new PrintWriter(file);
}
Above is my code, I am trying to make a PrintWriter that writes to a file I have made on my desktop called file.txt, however I am getting the error "unhandled exception type, file not found exception". I have looked at other posts and I'm unsure why I am still getting this error. I have also tried doing so without the File object. I was hoping for some guidance as to where I went wrong
The most important idea you have to understand here, is that your file may:
not be found;
have its descriptor locked (which means, that some other process uses it);
be corrupted;
be write-protected.
In all above cases, your Java program, triggering OS Kernel, will crush, and the exception will happen at the runtime. In order to avoid this accident, Java designers decided (and well they did), that PrintWriter should throw (meaning, it is a possibility to throw) FileNotFoundException and this should be a checked exception at compile time. This way developers will avoid more serious run-time problems, like program crush crush.
Hence, you either have to:
try-catch in your method that PrintWriter; or
throw the exception one level up.
I think, your question was about why that happens. Here is the answer for both - (1) why? and (2) how to solve it.
Java has an exception catch mechanism that helps you program better. You will have to handle an exception FileNotFoundException to warn that what will happen if the program cannot find your file Or you can throws this exception. I recommend learning about exception handling in Java.
This code can help you
public static void generateOutput() {
File file = new File ("C:/Users/me/Desktop/file.txt");
PrintWriter outputFile = null;
try {
outputFile = new PrintWriter(file);
} catch (FileNotFoundException e) {
// Handle if your file not found
e.printStackTrace();
}
}
Or
public static void generateOutput() throws FileNotFoundException {
File file = new File ("C:/Users/me/Desktop/file.txt");
PrintWriter outputFile = null;
outputFile = new PrintWriter(file);
}
Assuming your file exists in the given location, you need one of the following,
public static void generateOutput() throws Exception {... Your code ...}
Or
try {
//Your code
}
catch(FileNotFoundException fnne) {
// Precise exception catching example
}
catch(Exception e) {
// Not required, but adding it to catch any other exception you might face
}
You can always use precise exception in throws/catch. You need it because, PrintWriter can has compile time exception. Basically, it means if file is not found then it can throw exception and it is known at compile time. Hence you need to use one of the approach.
In addition to that, you make 2 lines into 1 as follows,
PrintWriter output = new PrintWriter(file);
You don't need to initialize the output object to null, unless you have it on purpose.
I am working on a function that enables the user to check a single student's assessment result. I use try and catch, but when I run the code, the system runs directly to the catch part, and the file's content is blank. I am not sure the reason about this problem. Here is my code:
System.out.println('\n' + "Please enter the Student's uni that you would like to call. Type 'exit' to leave");
String studentInfo = s.nextLine();
if (studentInfo.equalsIgnoreCase("exit")) {
userSelection = "exit";
}
boolean studentFound = false;
for (int i = 0; i < students.size(); i++) {
if (studentInfo.equalsIgnoreCase(students.get(i).getStudentUI())) {
studentFound = true;
try {
File singleStudentList = new File(studentInfo + " .txt");
PrintWriter writer = new PrintWriter(singleStudentList);
System.out.println(studentUniLists.get(i));
writer.println(studentUniLists.get(students.indexOf(studentInfo)));
writer.close();
} catch (Exception e) {
System.out.println("Problem writing the file. Please make sure the path is correct");
}
}
}
Thanks for helping!
My hunch is that your error is in one of these two lines:
System.out.println(studentUniLists.get(i));
writer.println(studentUniLists.get(students.indexOf(studentInfo)));
You haven't included code as to what studentUniLists is, so there is some guesswork here.
My guess is that students.indexOf(studentInfo) could be returning -1, so then when you do studentUniLists.get(-1) on a List, this is going to give you an IndexOutOfBoundsException. You should really only be catching the IOException, so that you can detect this kind of issue
Probably index out of bounds somewhere, e.g:
System.out.println(studentUniLists.get(i));
Are you sure studentUniLists has the index i?
Since you wrote there is no output and it just goes directly to catch.
As commented elsewhere, printing the actual exception helps.
You catch ANY Exception and you print to the console that this is file related problem. It does not have to be.
I suggest you add into your catch clause e.printStackTrace() to print the real problem. Secondly you should consider avoiding catching Exception as it is too broad. It might be worth catching exception that is related to file problems in the first place and leaving the rest uncaught.
Looking at the documentation - PrintWriter will be unlikely to throw errors. Comstructor may throw FileNotFoundException or SecurityException. CheckErrors is the function you need for checking file related errors.
https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#checkError(). Yet I believe you have non file related problem like NullPointerException or IndexOutOfBoundsException.
Hope this helps.
First, With Jdk 1.7 when you open the file use the try with ressources to let the jvm do the close automaticly.
File singleStudentList;
try (singleStudentList = new File(studentInfo + " .txt")) {
PrintWriter writer = new PrintWriter(singleStudentList);
}
Second, The error is getting by this : new File(studentInfo + " .txt")
you're always creating the empty file "true .txt"
Third, print the error by ex.printStackTrace();
I'm in a computer science (java) class right now and our task is to create a program that reads integers from an input.txt file (the professor will have this) and prints out all the integers into an output.txt file. Any exceptions/errors will need to be printed to an errors.txt file that our program creates. (We are learning about Exceptions in class now).
My program is able to read from an input file and print out just the integers to an output.txt, but I'm having problems printing out all the exceptions that might occur. For example, if the input file has "abc" as one of the lines, it should print out a message in the errors.txt file saying that it isn't an integer.
What happens with my program is that as soon as one exception is thrown, it doesn't keep going to print out all the other exceptions even if there are more to print. It just stops at that point.
So for example, something like this:
try{
while (fileScan.hasNext())
{
num = fileScan.nextInt();
}
}catch(Exception e)
{
erout.println(e); //prints the error to the file.
fileScan.nextLine();
}
erout is my PrintWriter object for the error.txt file. fileScan for the input.txt.
I'm just not sure how to get it to go through all of the input.txt file and keep track of all the exceptions it will throw, then print all those to an error.txt file. Any help would be appreciated, thanks. :)
You could move the while loop outside of the try statement.
while (fileScan.hasNext())
{
try{
num = fileScan.nextInt();
}catch(Exception e)
{
erout.println(e); //prints the error to the file.
fileScan.nextLine();
}
}
You need to re-order your while and try/catch:
List<Exception> exceptions = new ArrayList<>();
while (fileScan.hasNext()) {
try {
num = fileScan.nextInt();
// more code here to process num
} catch (Exception e) {
// Might also want to create a custom exception type to track
// The line/file that the error occurred upon.
exceptions.add(e);
fileScan.nextLine();
}
}
All you gotta do is move the try/catch within the while:
while (fileScan.hasNext())
{
try {
num = fileScan.nextInt();
}
catch (Exception e) {
erout.println(e); //prints the error to the file.
fileScan.nextLine();
}
}
while running a sort program for some custom data, I got some runtime exception which took up the whole console in eclipse. I would like to see the cause and the message of the exception.So I used a FileWriter as below to write the exception message. However the textfile is of 0 bytes, meaning nothing is written.
I also tried to run the code from the terminal(in linux -ubuntu) and using > to redirect the exception message ,but only got the output from system.out.println()
The FileWriter doesn't write the exception message.
Below is the relevant part of code.. Can someone tell me why this happened? I tried adding fw.flush() but it didn't make any difference.
public class MySort{
...
public static void sort(String[] data){
...
}
public static void main(String[] args) throws IOException {
String[] a = {"E","A","S","Y","Q","U","E","S","T","I","O","N"};
FileWriter fw = new FileWriter("sorterr.txt");
try{
sort(a);
}catch(RuntimeException e){
System.out.println("some text");
fw.write(e.getMessage());
fw.flush();
fw.close();
System.exit(0);
}
}
}
When run in Eclipse or Linux terminal, sorterr.txt is 0 bytes
In terminal, redirect also behaves the same. In short nothing inside the catch block prints out the values.
UPDATE:
It was a stackoverflow error ,that was the reason why it wasn't caught by the catch block (which was meant for RuntimeException)..
I detected this by setting
System.setErr(new PrintStream(new File("error.txt")));
thus,the stacktrace was printed in error.txt and this showed
Exception in thread "main" java.lang.StackOverflowError
at mysort.exercises.MySort.partition(MySort.java:67)
Try
File file = new File("sorterr.txt");
BufferedWriter output = new BufferedWriter(new FileWriter(file));
output.write(e.getMessage());
output.close();
The problem is that you are using FileWriter wrong.
How do I use exceptions and exception handling to make my program continue even if an exception occurs while processing certain files in a set of files?
I want my program to work fine for correct files while for those files which cause an exception in program, it should ignore.
Regards,
magggi
for(File f : files){
try {
process(f); // may throw various exceptions
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
You have to use the try/catch/finally blocs.
try{
//Sensitive code
} catch(ExceptionType e){
//Handle exceptions of type ExceptionType or its subclasses
} finally {
//Code ALWAYS executed
}
try will allow you to execute sensitive code which could throw an exception.
catch will handle a particular exception (or any subtype of this exception).
finally will help to execute statements even if an exception is thrown and not catched.
In your case
for(File f : getFiles()){
//You might want to open a file and read it
InputStream fis;
//You might want to write into a file
OutputStream fos;
try{
handleFile(f);
fis = new FileInputStream(f);
fos = new FileOutputStream(f);
} catch(IOException e){
//Handle exceptions due to bad IO
} finally {
//In fact you should do a try/catch for each close operation.
//It was just too verbose to be put here.
try{
//If you handle streams, don't forget to close them.
fis.close();
fos.close();
}catch(IOException e){
//Handle the fact that close didn't work well.
}
}
}
Resources :
oracle.com - Lesson: Exceptions
JLS - exceptions
I guess your new to programming as execeptions are a fairly fundermental concept, as problems can happen out of your control and you need to deal with it.
The basic premise is a try catch block.
try
{
//Your code here that causes problems
}
catch(exception ex)
{
//Your code to handle the exception
}
You 'try' your code, and if an exception is raised, you 'catch' it. And do what you need.
There is also an addition to the catch block in that you can add finally{} below it. Basically even if no exception is raised the finally code is still run. You may wonder the point in this, but its often used with streams/file handling etc to close the stream.
Read more on java exceptions here in tutorials written by Sun (now Oracle)- http://download.oracle.com/javase/tutorial/essential/exceptions/
try
{
//Your code here that causes problems
}
catch(exception ex)
{
//Your code to handle the exception
}
finally
{
//Always do this, i.e. try to read a file, catch any errors, always close the file
}
The question you may ask is how do you catch different exceptions, i.e. is it a null reference, is it divide by zero, is it no file found or file not writeable etc. For this you write several different catch blocks under the try, basically one catch for each type of exception, the use of "exception" is basically a catch all statement, and like in stack of if statements if an "exception" is the first catch block it will catch everything, so if you have several catch blocks ensure exception is the last one.
Again, this is a useful but large topic so you need to read up about it.
Since you are doing multiple files, you need to basically do a loop and within the loop is contained the try/catch block.
so even if one file fails, you catch it, but carry on running, the code will then loop around onto the next file unhindered.
just catch the excpetion it may throw and do nothing with it; eat it as people say :)
But at least log it!
Very concise example:
try {
your code...
} catch (Exception e) {
log here
}
Typically, I would have done this.
ArrayList<Entry> allEntries = getAllEntries();
for(Entry eachEntry:allEntries){
try{
//do all your processing for eachEntry
} catch(Exception e{
ignoredEntries.add(eachEntry);
//if concerned, you can store even the specific problem.
} finally{
//In case of resource release
}
}
if(ignoredEntries.size() > 0){
//Handle this scenario, may be display the error to the user
}
FileSystemException may be the specific exception you are looking for.
Although, a better idea for beginners is to catch an exception and print it using
System.out.println(e);
where e is the caught exception.
public class Main
{
public static void main(String args[])
{
int a=10;
try
{
System.out.println(a/0); //Here it is not possible in maths so it goes to catch block
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception");
}
}
}
output:Arithmetic Exception
Exception in java are runtime error which can be handled by the program, the process is called as exception handling. Parent class of exception is Throwable.
Exception : Exception are those runtime error which can be handled by program.
Error : Those runtime error which can’nt handled by the program.
Tools used to handle Exception:
Try
Catch
Finally
Throw
Throws
more