This question already has answers here:
Dumping state of variables on Exception
(6 answers)
Closed 3 years ago.
Background:
I frequently write java code on Apache Spark for ETL job, usually on cloudera CDH cluster with every data source set up. The data I'm processing is usually dirty. For example for zip code, I was thinking I could use an integer to represent it but there could exists some record like "85281-281" and we couldn't parse it as a integer. Thus an exception is thrown and the program halt with a bunch of stack trace.
Previously I have to write the code based on my assumption, run it on the cluster, failed with a huge bunch of stack trace. Including the line number that throws the exception. But it is really time consuming to find the root cause especially I don't the specific line of the data.
So I'm think the following:
The code shouldn't stop when errors occurs. This is easy, use Java's exception handling system can easily achieve this.
I want to know the variables content in current stack which cause the error, so that I could find the root cause of the input (specific line in the input). Not just the line number that throws the exception. For example NullPointerException, I want to know the raw input data, which specific line in the input file caused this.
We have e.printStackTrace() to show the all function call in the stack trace. Can we do it better by also showing the content on top of the current stack? Just like a debugger do?
Of course I would manually print out all variables by hand coding. But I just want to know if there is a specific function that a debugger would use to show those variables.
For example, if you have the following code
final String line = ... // get next line
processLine(line);
you could transform it to
final String line = ... // get next line
try {
processLine(line);
} catch (RuntimeException e) {
System.out.println(String.format("Oh no, an exception! The line was '%s'", line);
e.printStackTrace();
// ... any recovery logic
}
You could catch not just RuntimeException's, but other exceptions as well. You could also log to some logger and not to console.
Related
I am designing an eclipse plugin which reads the stack trace from console when an exception occurs.
Plugin is basically used for content based searching when an exception happens. The user explicitly selects the keywords from the stack trace but plugin implicitly need the line from the source code causing the exception, so that together the source code line and keywords can be used for better search results. In that case Plugin can't make changes to the source code.
Console gives me the file, package and the line number but I want the corresponding line from the source code which caused the exception.
For example if i have an exception like
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 10, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at Test.main(Test.java:13)
I would want the line 13 from the source code of Test.java
You may probably not have the exact reusable code, but this something which you can explore.
In the Throwable class you can access the StackTrace Elements List and get the Line numbers of the code from where it was propogated.
Note:
At times you may get more than one StackTrace Elements in the
exception object, you may to then iterator and get the one you want
the line number for.
Something like
catch(Throwable e){
e.getStackTrace()[e.getStackTrace().length - 1].getLineNumber();
}
I'm working on a program that takes user input in the form of a textfield and two comboboxes and displays the totals below. I have all of that working, but now I am trying to have the numbers selected saved and reread the next time the program is opened. I was lead to believe this is done with datainputstream and dataoutput stream.
I have coded both into my program and it compiles fine, but when I try to enter new data in, it catches it and closes (I coded the system.exit in to find out if its working or not).
I'm sure its something with my syntax, but I can't find it.
The whole program is here: http://pastebin.com/9L686Pxx
Edit: The formatting is a lot easier than I thought, so this is the block of code that is causing the program to exit.
try
{
int economyCount = input.readInt();
int standardCount = input.readInt();
int advancedCount = input.readInt();
int exceptionalCount = input.readInt();
int redCount = input.readInt();
int greenCount = input.readInt();
int blueCount = input.readInt();
int yellowCount = input.readInt();
}
catch(IOException io)
{
JOptionPane.showMessageDialog(null, "The program could not read the data. Please check the disk drive and then run the program again.", "Error", JOptionPane.INFORMATION_MESSAGE);
System.exit(1);
}
You need to print out or log the stacktrace (or at least the error messages) for the exceptions that you are catching. Currently, your code is throwing away the evidence of what is causing the problem. (Hint: look at the javadoc for Exception.printStackTrace().)
Alternatively, run your application using your IDE's debugger, and set a breakpoint on the System.exit call that is causing the application to exit. Then examine the exception to find its classname and message.
The chances are that this will give you enough evidence to allow you to identify and fix the root problem. If not, add the complete stacktrace to your Question.
Based on the fact that the exception occurred at that point, I suspect that the problem is that you are attempting to read data that hasn't been written yet. It looks like the sequence is:
Open output ... which truncates the existing file.
Open input
Attempt to read 4 values from input. Ooops! Nothing there yet ... exception.
Once you have gotten past that, there are other problems with the way you are reading and writing:
Neither the read or write code seems to reset the data streams to the start.
The read phase is writing 4 ints and the write phase is writing 8 ints ... in a different order.
IMO, trying to reuse the same DataInputStream and DataOutputStream objects is a bad idea. You should recode it to, "open, read, close" and then "open, write, close" each time ... in the actionPerformed method. The input and output variables should be local variables, not instance variables.
The belated evidence of your stacktrace confirms this diagnosis.
If you're using DataInputStream.readFully() you need to catch EOFException separately. It means you've exhaused the input, so you should close it and stop reading.
I'm working on a Spotify puzzle (viewable here). I'm writing the solution in Java and I've gotten my code to pass their two example inputs in Eclipse, on ideone.com, and through Terminal on my osx, all without errors. However whenever I submit to the Spotify bot I get the following minimalist response:
We have tested your solution, and while doing so we unfortunately
discovered the following error: Run Time Error
An exception was not caught
Here's basically what I do to read in input:
scn = null;
try {
scn = new Scanner(System.in);
if(scn.hasNext()){
strIn = scn.nextLine();
//do work on first line of input
}
if(scn.hasNext()){
strIn = scn.nextLine();
//do work on second line of input
}
//do work on the rest of the lines
while (scn.hasNext()) {
strIn = scn.nextLine();
if(/*reached last line*/){
break;
}
}
}
catch(Exception e){
System.out.println("Exception caught");
System.out.println(e.getStackTrace());
} finally {
if (scn != null) {
scn.close();
}
}
You can view my complete solution here. Note that my actual submission declares my class public, as per the Spotify submission guidelines.
Since the problem requires only simple I/O from stdin to stdout, it seems like I only need to account for any exceptions that may be thrown when I'm reading in input within my try block. I provide a catch block for all Exceptions (bad form I know) but shouldn't that handle it? Maybe I'm neglecting some exceptions that could be popping up elsewhere?
It may be that I'm not accounting for some small peculiarity about how the Spotify bots parse input, but their response message and guidelines make it hard to pinpoint where exactly the problem is. I apologize if this question is too localized - other Spotify puzzle questions were seen this way - but I figure my i/o and exceptons questions are broad enough, and perhaps people have some good answers on how the Spotify bots might work. Also, it's been a while since I've coded in Java, so any other comments are certainly welcome.
Just to make it official, the exception that was being raised was not an I/O exception, like I was thinking, but actually an integer overflow exception. I needed to change the data type of the variable holding track plays to a long from an int. The test data Spotify was using must have had really large numbers that my ints couldn't hold, and that's why the program kept breaking! Hope this helps people.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
exception handeling, creating log and continue the program in JAVA
I am designing a program in JAVA that captures results in about 10 iterations, and after that i have to write all the results in a log file, I need a solution that if any exception occurs then it should be written on my text file and secondly the program must not stop, it must go on till the last iteration is completed... ie if some error occur on any part of any iteration, it must be mentioned within my results by the name of error and the program must not stop here, it must go on and update my log file
see this just for example: because my class is around 1800 lines can't paste all here.
float j,i,t;
int []a={1,2,0,3,4,5};
int []b={6,6,9,3,4,5};
for(int i=0;i<6;i++)
{
j=2/a[i];
i=3/b[i];
t=4/b[i];
}
so here due to 0 in list of values of arrray an exception occurs, thus stopping the whole iteration, i want that to skip, if some exception occur the loop must not be broken, it just leave out that exception part and write on a text file.
try this:
float j;
int []a={1,2,0,3,4,5};
for(int i=0;i<6;i++)
{
try{
j=2/a[i];
catch(Exception e){ //a more specific exception would be preferable, but I don't know what other exceptions may occur here
System.out.println("Exception occurred at iteration: "+i);
}
}
Edit: just realised, having the value in the print statement might also cause an exception if the array is too small.
Second Edit: Exception handling isn't as efficient as simple checks i.e. if(a[i] == 0), so using checks would be a more efficient way of going about this.
I think you should read the answers to this question to learn more about exception handling.
can anyone tell me how to read multiple lines and store their value.
eg:file.txt
Probable Cause: The network operator has issued an alter attribute command for
the specified LCONF assign. The old value and the new value are show
Action Taken : The assign value is changed from the old value to the new
value. Receipt of this message does not guarantee that the new attribute
value was accepted by clients who use it. Additional messages may be.
Probable Cause: The network operator has issued an info attribute command for
the specified LCONF assign. The default value being used is displaye
Action Taken : None. Informational use only.
In the above file, Probable Cause and Action Taken are the column of a database table. And after Probable Cause: those are the value to be stored in the database table for probable cause column, same goes with action taken.
So how can i read the multiple lines and store their value? I have to read the value for probable cause until the line comes with Action Taken. I'm using BufferedReader and the readLine() method to read one line at a time. So can anyone tell me how to read directly from probable cause to action taken no matter how many line comes between them.
The simplest way is probably to just keep a List<String> for each value, with loops something like this:
private static final String ACTION_TAKEN_PREFIX = "Action Taken ";
...
String line;
while ((line = reader.readLine()) != null)
{
if (line.startsWith(ACTION_TAKEN_PREFIX))
{
actions.add(line.substring(ACTION_TAKEN_PREFIX))
// Keep reading the rest of the actions
break;
}
causes.add(line);
}
// Now handle the fact that either we've reached the end of the file, or we're
// reading the actions
Once you've got a "Probable Cause" / "Actions Taken" pair, convert the list of strings back to a single string, e.g. joining with "\n", and then insert in the database. (The Joiner class in Guava will make this easier.)
The tricky bit is dealing with anomalies:
What happens if you don't start with a Probable Cause?
What happens if one probable cause is followed by another, or one set of actions is followed by another?
What happens if you reach the end of the file after reading a probably cause but no list of actions?
I don't have the time to write out a complete solution now, but hopefully the above will help to get you going.