Viewing runtime exception message from java program - java

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.

Related

Getting file not found exception with PrintWriter and File

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.

Write file in linux with java isn't working

a java code i've been working in Windows worked perfectly, but when i tried to run it in linux didn't work (i.e it didn't create the file and therefore didn't write)...these are the functions i'm using:
BufferedWriter writer =null;//
String directory= "folder/";
java.io.File directory1 = new File(directory+"resultado");
String directory2;
directory1.mkdirs();
directory2=directory+"resultado/";
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(directory2+"resultado.txt"), "utf-8"));
writer.write("something");
writer.newLine();
} catch (IOException ex) {
System.out.println("ERRORR!!!!");
ex.printStackTrace() ;
// report
} finally {
try {writer.close();} catch (Exception ex) {//ignore}
}
}
Even thoug i have the catch IOException to write "Error" it gives me the error
Exception in thread "main" java.lang.NullPointerException
at memoria.bosques.imprimirenarchivos(bosques.java:17281)
at memoria.bosques.main2(bosques.java:18096)
at memoria.bosques.main(bosques.java:18139)
The folder of the directory is created, but it seems the functions don't create a file to write on it...what can i do?
I suggest writer is null in your finally block, because you got a prior exception, which you didn't tell us about. Either test it for null before closing, or use try-with-resources.
And when you get an exception, don't just print out "ERROR!!!!". It's useless. Print the exception.
And when you call a method like mkdirs() that returns a result, don't ignore it.

Beginner Java Task file writer

I am trying to make a java program that appends text into an existing document. This is what it has gotten me at:
import java.util.*;
import java.io.*;
public class Main
{
public main(String args[])
{
System.out.print("Please enter a task: ");
Scanner taskInput = new Scanner(System.in);
String task = taskInput.next();
System.out.print(task);
PrintWriter writer = new PrintWriter("res\tasks.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();
}
}
I have some errors and do not know how to fix them. I looked at the Bufferedwriter but I don't know how it's used, and yes I have looked javadocs. C++ was not nearly this complicated. Once again, I want to know how to make the program append text to an existing file. It should be efficient enough to make into an app. Are there any good resources to teach how to write/append/read files?? javadoc is not doing it for me.
The main() method in Java has to have the following signature
public static void main(String[] args)
Without the method being declared as above, JVM would fail to run your program. And, just like you closed the PrintWriter, you need to close your Scanner too.
I suggest you get the basics of Java down before diving into File I/O because this API would throw a lot of checked Exceptions too and for someone this new to Java it would just be terribly confusing as to what the try catchs or throws are doing.
try this,
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("tasks.txt", true)));
The following should work:
public static void main(String[] args) {
try{
Formatter out = new Formatter("fileName.txt");
out.format("Write this to file");
out.close();
} catch (Exception e) {
System.out.println("An error occurred");
}
}
This is using a Formatter object to create a file (if it doesn't already exist) and then you can use the method "format" just like you would use any print method to write to the file. The try and catch is necessary for it to compile b/c the constructor of the Formatter class throws an exception that must be caught. Other than that, just make sure you type:
import java.util.Formatter;in the beginning of your file.
And btw, C++ is NOT easier than Java lol. Cheers.

Error handling in java

Am running .exe file from java code using ProcessBulider, the code I have written is given below. The .exe file takes Input.txt(placed in same directory) as input and provide 3 output file in same directory.
public void ExeternalFileProcessing() throws IOException, InterruptedException {
String executableFileName = "I:/Rod/test.exe;
ProcessBuilder processBuilderObject=new ProcessBuilder(executableFileName,"Input.txt");
File absoluteDirectory = new File("I:/Rod");
processBuilderObject.directory(absoluteDirectory);
Process process = processBuilderObject.start();
process.waitFor();
}
this process is working fine by call ExeternalFileProcessing(). Now am doing validation process, If there is any crash/.exe file doesn't run, I should get the error message how can I get error message?
Note: It would be better that error message be simple like run successful/doesn't run successful or simply true/false, so that I can put this in If condition to continue the remaining process.
You can add exception handlers to get the error message.
public void externalFileProcessing() {
String executableFileName = "I:/Rod/test.exe";
ProcessBuilder processBuilderObject = new ProcessBuilder(
executableFileName, "Input.txt");
File absoluteDirectory = new File("I:/Rod");
processBuilderObject.directory(absoluteDirectory);
try {
Process process = processBuilderObject.start();
process.waitFor();
// this code will be executed if the process works
System.out.println("works");
} catch (IOException e) {
// this code will be executed if a IOException happens "e.getMessage()" will have an error
e.printStackTrace();
} catch (InterruptedException e) {
// this code will be executed if the thread is interrupted
e.printStackTrace();
}
}
But it would be better to handle it in the calling function by put a try catch handler in the calling function and handling it there.
Is it a third party .exe or do you have access to its sources? If so, you could work with basic System outputs (for example couts to the console).
Those outputs can be redirected to your java app using something like this:
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = "";
while ((line = br.readLine()) != null) {
if(line.equals("something")) {
// do something
}
}
br.close();
This is how i do things like that and it works very well in general. But i must admit, that i can not say/garuantee, that this is THE way to do it. A more advanced approach might be the use of StreamGobbler (see Listing 4.5) to handle the outputs of the .exe.
Let me know if it helped you or not.

Having trouble writing to a file

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.

Categories