I'm using Eclipse to debug a Java application. Somewhere in the code I get an exception and the stack trace:
Caused by: java.io.EOFException: The connection has been reset while reading the header
at com.gemstone.gemfire.internal.cache.tier.sockets.Message.fetchHeader(Message.java:583)
at com.gemstone.gemfire.internal.cache.tier.sockets.Message.readHeaderAndPayload(Message.java:599)
at com.gemstone.gemfire.internal.cache.tier.sockets.Message.read(Message.java:542)
at com.gemstone.gemfire.internal.cache.tier.sockets.Message.recv(Message.java:1029)
at com.gemstone.gemfire.cache.client.internal.AbstractOp.attemptReadResponse(AbstractOp.java:158)
at com.gemstone.gemfire.cache.client.internal.AbstractOp.attempt(AbstractOp.java:363)
at com.gemstone.gemfire.cache.client.internal.ConnectionImpl.execute(ConnectionImpl.java:229)
at com.gemstone.gemfire.cache.client.internal.pooling.PooledConnection.execute(PooledConnection.java:321)
at com.gemstone.gemfire.cache.client.internal.OpExecutorImpl.executeWithPossibleReAuthentication(OpExecutorImpl.java:646)
at com.gemstone.gemfire.cache.client.internal.OpExecutorImpl.execute(OpExecutorImpl.java:108)
... 11 more
How do I get the whole stack instead of the ... 11 more?
You have the entire stack.
This is only part of a stack trace. Directly before this was another piece. Look at the bottom lines of this one, and the top lines of the previous one. You'll see them match up. The stack trace began with a section that doesn't begin with "Caused by".
The "Caused by" exception is hiding parts of the stack trace that are verbatim copies of stack trace entries in its parent. In other words, Java doesn't show the entire stack up to main() for every cause - it just shows what you haven't seen already. See the Throwable.printStackTrace() documentation.
The "Caused by" is filled when you provide a cause when creating a Throwable. Look at the constructors for it. This is done when a piece of code catches a low-level exception and then wants to rethrow it as a different exception class.
the answers above are not accurate, every time the stack show the words "caused by" it means that the exception went through one or multiple methods until it was caught, and then thrown again. This could happen many many many times, the stack trace is not a loop, it is a single direction, so no, the stuff at the top does not relate to the stuff at the bottom, the most important part IS at the bottom, that is the root of the exception, so if you would have:
Exception in class main: blah blah blah
...lines of code...
caused by FileNotFoundException
...lines of code...
caused by: MalformedURLException
...lines of code...
caused by: NullPointerException
then you would not want to focus so much on the FileNotFoundException, but you would want to focus more on the NullPointerException. Like say you had a properties file with a file name in it. If accidentally used mykey, to find the property "myKey", then the propertiesResource would return a null, that would then get thrown all the way through all the lines of code (hopefully) to your application where the last catch block is. . . wich, at this piont, it would be "wrapped" not as a nullException, but as a FileNotFoundException. . .
We might be diverging from the actual problem he's facing. I was having similar problem and it turns out I had my Limit console out put box check marked. After I removed it I was able to see the full stack trace.
Steps:
Right click on console || ctrl + click if mac
go to preferences and follow the above instructions
I think it means that the Exception was caught and packaged into another 11 times before printStackTrace was called.
Try and figure out the output of the following program for better understanding:
public class PrintStackTrace {
public static void main(String[] args) {
try {
level1();
} catch (Exception e) {
e.printStackTrace();
}
try {
level2();
} catch (Exception e) {
e.printStackTrace();
}
}
static void level2() throws Exception {
try {
level1();
} catch (Exception e) {
throw new Exception(e);
}
}
static void level1() throws Exception {
try {
throwingMethod();
} catch (Exception e) {
throw new Exception(e);
}
}
static void throwingMethod() throws Exception {
throw new Exception("throwingMethod");
}
}
As Ed says, it is showing the entire stack, but leaving out information that you've already seen. See Throwable#printStackTrace()
Quoting from there:
Note the presence of lines containing the characters "...". These
lines indicate that the remainder of the stack trace for this
exception matches the indicated number of frames from the bottom of
the stack trace of the exception that was caused by this exception
(the "enclosing" exception). This shorthand can greatly reduce the
length of the output in the common case where a wrapped exception is
thrown from same method as the "causative exception" is caught
Often an exception is wrapped; created with another exception as the cause:
try {
// something which causes an Exception
} catch (Exception e) {
throw new SpecificException("help", e);
}
In this case, displaying the stacktrace will create the ... 11 more that you see.
I have never seen that, but try this
public void problemFunction(){
try{
//your code
catch(Exception ex){
ex.printStackTrace();
}
}
or
public void problemFunction(){
try{
//your code
}
catch(Exception ex){
System.out.println(ex);
StackTraceElement[] arr = ex.getStackTrace();
for(int i=0; i<arr.length; i++){
System.out.println(arr[i].toString());
}
}
}
There is a vmargs option
-XX:-OmitStackTraceInFastThrow
which might help in some situations.
To simplify the accepted answer let us consider a simple notation.
Exception in main ……
At A
At B
At C
Caused by ….
AT P
At Q
AT R
AT A - > { THIS ONE IS REPEATED , But slightly with line
number changes } .
MISSING 2 MORE { THOSE 2 ARE NOTHING BUT B AND C .}
Caused by …
At X
At Y
At P - > { THIS ONE IS REPEATED , But slightly line
number changes }
Missing 5 More ( Those 5 are nothing but Q,R, ,A,B,C )
Hence you have the entire stack.
But MAKE SURE CHECK BOX FOR “limit console output” is NOT checked under run/debug drop down --> console in eclipse preferences.
You can use the following code to get more clarity.
try {
// code causing exception
}
catch(Exception ex){
Throwable exThrowable=ex;
while(exThrowable!=null) {
System.out.println(exThrowable);
StackTraceElement[] arr =
exThrowable.getStackTrace();
for(int i=0; i<arr.length; i++){
System.out.println(arr[i].toString());
}
exThrowable=exThrowable.getCause();
}
Related
I'm a beginner in java writing an frontend for a webservice.I have to validate the input to get useful error messages for the user.Currently it works this way:
public Object zipVal(String zip)
{
try
{
if (zip.length() == 5)
{
val.setZip(Integer.parseInt(zip));
return val.getZip();
} else
{
return lengthError;
}
} catch (NumberFormatException e)
{
return formatError;
}
}
for zip Codes.Using Objects to declare the return type is not what I want tho(and is afaik discouraged),but I'm not sure how I should handle wrong inputs other than that.Should I just return null for every Exception and invalid input and handle such things in another method?
Edit:Added something to actually throw an Exception...
Yeah, exception handling might be one of the trickier things to consider (if one comes from a C programming background for example, where we used to be happy with < 0 return code for indicating erroneous program flow).
Normally you are pretty safe off by catching other API:s you integrate with and encapsulate them in your own exception (sort of masking them away), but by doing so don't forget to chain the original exception into your own with this constructor (and/or derivatives of such):
public MyException(final String message, final Throwable cause) {
super(message, cause);
}
One surely see alot of:
catch (Exception) {
return null;
}
and such in code as well, I wouldn't say that this is "good" object orientation, but it is still common and could be used in special occasions.
And also, its usually very important what you do (how to handle) when you catch the exception, someone told me that programing is 90% about error control and 10% about functionality :)
Here are some tutorials/resources:
http://docs.oracle.com/javase/tutorial/essential/exceptions/
http://howtodoinjava.com/2013/04/04/java-exception-handling-best-practices/
If you are returning a value, then there is no need to handle the exception. It is better you declare that the method may throw the exception.
NumberFormatException is a RunTimeException. So if you wish to handle it, then better return an invalid zip (say -1) to let the caller know that something went wrong.
Otherwise, declare that you will throw a Custom Exception if NFE occurs.
This snippet may be useful.
public int setZipVal(String zip) // throws CustomException
{
try
{
if (zip.length() == 5)
{
val.setZip(Integer.parseInt(zip));
return val.getZip();
}
} catch (NumberFormatException e)
{
// Log the error and return invalid zip
return -1;
// OR throw custom exception
throw new CustomException("Length Error"));
}
}
I'm a relative newbie to custom error handling in Java, and I'm trying to figure out how to use catch statements to deliver specific messages inside of an if statement. I wanted to get some extra sets of eyes to look at what I'm trying to do and offer feedback before I completely overthink this and overdo it too badly.
Consider:
We have a directory of hourly log files and I have an on-demand reporting job creates a concatenation of all today's log files created so far. I want to add a step that checks for the existence of a concatenated log file, deletes it then creates it if present, or just creates it if it's not present. With the code below, I'm returning an exception if, for some reason, the new file cannot be created.
try {
File file = new File (destinationPath + "todayToNowLogFile.csv");
if(file.exists())
{
if(file.delete())
{
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Existing file cannot be deleted.")
}
} else {
System.out.println("File will be created.");
}
}
//
catch(Exception e) {
System.err.println("Exception: ");
System.out.println("Exception: "+ e.getMessage().getClass().getName());
e.printStackTrace();
}
Now, in the case where the file cannot be deleted, I would like to display the exception preventing file deletion. First, I would need to catch that error, but then where do I put the try?
Doing something like this...
try
{
if(file.delete())
{
System.out.println(file.getName() + " is deleted!");
}
}
else {
catch(Exception eDel) {
System.err.println("Exception: ");
System.out.println("Exception: "+ eDel.getMessage().getClass().getName());
eDel.printStackTrace();
}
}
....interrupts the if...then block. I'm not sure how to insert a try...catch within an if...then. Is there a way to do this? Or does my original code catch EVERY error associated with ANY operation on the file defined in the try block, and I would need to put if...then logic in the catch block, something along the lines of this pseudocode....
catch(Exception e) {
if(exception relates to file deletion) {
"File delete exception " + exceptionMessages;
} else if(exception relates to file creation) {
"File create exception " + exceptionMessages;
} else if(other exception) {
"other exception " + exceptionMessage;
} else {
"no exceptions encountered"
}
}
What's the most appropriate way to handle this type of situation?
You should think of try/catch as any other statement. So you can put it inside any of two branches of if/then/else statement, but it have to be whole inside:
if(statement){
...
try{
...
}catch(...){
...
}
...
}else{
...
try{
...
}catch(...){
...
}
...
}
If you have to catch multiple exceptions you can achieve this by multiple catch parts:
try{
...
}catch(Exception1 e1){
...
}catch(Exception2 e2){
...
}catch(Exception3 e3){
...
}
What you want here is to create your own Exception class.
To create an exception class say you need to extend Exception class. Here's an example.
Lets say my custom exception class should be named as MyFileErrorException
So I create a new class like this -
class MyFileErrorException extends Exception {
private String message = null;
public MyFileErrorException() {
super();
}
public MyFileErrorException(String message) {
super(message);
this.message = message;
}
public MyFileErrorException(Throwable cause) {
super(cause);
}
#Override
public String toString() {
return message;
}
#Override
public String getMessage() {
return message;
}
}
Now I need to throw this exception at will. So in Your case you wantto catch File delete exception so the code will like this -
if(file.delete())
{
System.out.println(file.getName() + " is deleted!");
} else {
try{
System.out.println("Existing file cannot be deleted.")
throw new MyFileErrorException("File Could not be deleted val is null");
}catch(MyFileErrorException ex){
//Do wahtever you want to do
}
}
At first you should check if any method could throw any specific Exceptions. You could do this by looking into the Javadoc or use your favorite IDE.
If you catch Exception as the Exception class, it catches every Exception that is subclass of it.
If you want to have specific Exception handling, e.g. for an IOException like in the delete() method, you can catch every specific Exceptionclass or use multi-catch in Java 7
try {
do regular code that can throw exceptions
} catch(Exception e) {
it catches every Exception that is a subclass of Exception.
You handle every exception raised in the try block above by the same way
}
If you want to handle exceptions in different ways, e.g. print different messages, just do this like the following example:
try {
do sth
} catch (SpecificExceptionclass sec) {
do sth specific for this exception
} catch (AnotherExceptionClass aec) {
do sth else
}
Or just use Multicatch in Java 7, if you want to have same exception handling for some specific exception classes:
try {
do sth
} catch (SpecificExceptionclass | AnotherExceptionClass e) {
do sth specific for this exception
}
To achieve different Exceptions thrown in your code the methods should at least throw different exceptions. In your example with file.exists() and file.delete() there's only an IOException thrown by your code, so there is no use of specific exception handling.
I think it would be a good idea to put your code in a function that returns true or false.
1: True means the file does not exist and was created
2: False means the file exists and was deleted.
3: An exception if the file exists but cant be deleted.
Also provide a separate function to determine if the file exists or not.
Your javadoc at the top of your functions should explain the above so the caller of your functions don't have to look at their content to determine how to use them.
Note an exception is an unusual event and shouldn't be thrown to indicate the state of inserting/deleting. It should be reserved for unusual conditions which the caller normally wouldn't encounter.
A note on exceptions: If you have a large project with 1000 classes each of which has on average 20 functions, that's 20000 functions. Its not practical to pepper each function with excessive exception handling (such as checking for nulls passed in as arguments). A solution to this is to handle checked exceptions in the java language (FileIO) and let (the bulk) of unchecked exceptions ripple up the function call chain until you leave all your business logic and are about to display the results. You only catch them if you want to add additional information to the exception before rethrowing it. Example: adding the primary key value of the record of an SQLExeption being thrown so you know what record is causing problems. Just before you return to the user, log the stack trace and display a simplified message to the user (not the stack trace). The caller of your function should read its javadoc to see how to use it. If he violates your javadoc, the function may or may not throw an exception. Its his reponsibility to follow the javadoc. Last point: your project should have general coding policies for the entire project to prevent some types of exceptions from accidently being introduced by the caller such as: all functions are not epected to recieve nulls as arguments or will return a null unless specified in its javadoc. All functions will accept as arguments (or return) empty lists or empty strings correctly unless specified in their javadoc.
I have to write logic for detecting what line of code was exception thrown so we can go fix that issue later. The exception object's getStackTrace() gives us a list of stacktrace each with level. I am not interested in getting lowest place where exception was thrown but rather my class method which was responsible in passing parameters.
Here is an example of what i am asking
class Test {
void divide() {
try{
float i = 1/0
}
catch(Exception e){
def v = e.getStackTrace()[0]
println v.getClassName()
}
}
}
This would print class java.math.BigDecimal but i am interested in getting Test class so i can go to it's divide and fix this bug. Now, Test appears in some nth line which i cannot know in run time. One approach would be to iterate stacktrace list and try finding class which is custom developed but how to detect that? Or if there is some library function that already does that it would be great.
Try this:
println e.stackTrace.find {
it.className == 'Test' && it.methodName == 'divide'
}
Or, I guess you want to check all levels of stacktrace, then:
Throwable t = e
StackTraceElement found = null
while (!found && t) {
found = e.stackTrace.find {
it.className == 'Test' && it.methodName == 'divide'
}
t = e.cause
}
println found
I have a piece of code, that throws NullPointerException sometimes. So far not really interesting. But the Exception occurs in a line, that does not reference any object.
try
{
parser.parse(input);/*line 186*/
}
catch(Exception e)
{
//NPE happens in the next line?
throw new SAXException("Error parsing document", e);/*line 190*/
}
Here the Stacktrace
java.lang.NullPointerException
at com.tejoe.MyXMLParser.parse(MyXMLParser.java:190)
at com.tejoe.MyXMLParser.parse(MyXMLParser.java:168)
....
It happened only twice in the last three months and the code run at least a hundred thousand times.
I already decompiled my code, to make sure the line information were correct and yes they are.
Additional Test
There seems to be something special with SAXException. I did the following test:
import org.xml.sax.SAXException;
public class Test
{
public static void main(String[] args) throws Exception
{
new SAXException("Error", new NullPointerException()).printStackTrace();
}
}
I got the following output
java.lang.NullPointerException
at Test.main(Test.java:7)
Caused by: java.lang.NullPointerException
... 1 more
Solution:
SAXException overrides toString method, to return the Name of the cause Exception.
Now I only wonder, that I did not get the caused by output in the production environment (AIX JAVA)
I wrote following code and generated null pointer exception. It came on line 45 as follow,
Exception in thread "main" java.lang.NullPointerException
at inheritance.parent.Child.main(Child.java:45)
import org.xml.sax.SAXException;
public class Child {
public static void main(String[] args) throws SAXException {
try{
Child c1 = null;
c1.i=0;
} catch(Exception e){
throw new SAXException("Error", e); //Line : 45
}
}
}
The error for your code is proper. You need to find which object you are getting null.
Your code must have changed since you made your last release. This will mess up the line numbers, since they are based on the code at the time it was compiled.
It looks like you've removed some code from that file since the release, meaning that the line numbers are larger than they should be.
Replace your line :
throw new SAXException("Error parsing document", e);
with
e.printStackTrace();
you will find the right error line.
I have 2 classes, one that implements a double lookup( int i);
and one where I use that lookup(int i) in solving a question, or in this case printing the lookup values. This case is for an array.
So I read the exception documentation or google/textbook and come with the following code:
public double lookup(int i) throws Exception
{
if( i > numItems)
throw new Exception("out of bounds");
return items[i];
}
and take it over to my class and try to print my set, where set is a name of the
object type I define in the class above.
public void print()
{
for (int i = 0; i < set.size() - 1; i++)
{
System.out.print(set.lookup(i) + ",");
}
System.out.print(set.lookup(set.size()));
}
I'm using two print()'s to avoid the last "," in the print, but am getting an
unhandled exception Exception (my exception's name was Exception)
I think I have to catch my exception in my print() but cannot find the correct formatting online. Do I have to write
catch exception Exception? because that gives me a syntax error saying invalid type on catch.
Sources like
http://docs.oracle.com/javase/tutorial/essential/exceptions/
are of little help to me, I'm can't seem to grasp what the text is telling me. I'm also having trouble finding sources with multiple examples where I can actually understand the coding in the examples.
so could anybody give me a source/example for the above catch phrase and perhaps a decent source of examples for new Java programmers? my book is horrendous and I cannot seem to find an understandable example for the above catch phrase online.
I wouldn't throw Exception ever.
In your case, IndexOutOfBoundException or InvalidArgumentException would eb a better choice. As these are not checked Exceptions, you don't need to catch them.
public double lookup(int i) {
if(i >= numItems) // assuming numItems is not items.length
throw new IndexOutOfBoundException("out of bounds " + i + " >= " + numItems);
return items[i];
}
Note: the check should be >=
Your print() method will now compile unchanged.
What is Exception?
Exceptions are for exceptional conditions. Conditions that normally do not occur. Take an example you went to withdraw money and your account has 100 balance and you asked for 200 then ATM should tell you that you have insufficient balance.
Types of Exceptions
Checked Exception
These are conditions where application wants to recover from it. Like example given above application will give you error and will continue working.
Error
This is an exceptional condition which is external to application. We say OutOfMemoryError when there isn't enough memory available and application can not recover from it.
Runtime Exception /Unchecked Exception
These exceptions are applications exception but in this case application can not recover from it. E.g NullpointerException if value is null and you try do something nasty with it.
so of above three only checked exceptions need to be cached.
How to throw and Catch Checked Exception
Exception or any subclass of Exception is a checked exception. A checked exception can be thrown using throw clause. Once you throw an exception it becomes mandatory for you to include that in method declaration using throws clause.
So whoever want to use this method will now have to handle that exception. Handling exception means invoking alternative flows. Like in our case we displayed text to user "Error Invalid account number."
Calling function can also choose to propagate exceptions by adding throws clause for those exceptions which are thrown by method it is calling.
Generate:
public static double withdraw(int i) throws Exception {
if (i <= 0)// Out of bounds
throw new Exception("Invalid Account Number");
return 0.0;// something;
}
Handle:
try {
withdraw(0);
} catch (Exception e) {
// do something with exception here.
// Log the exception
System.out.println("Error Invalid account number.");
}
Propagate:
public static double callWithdraw(int i) throws Exception {//Propagate exceptions
return withdraw(i);
}
Try this
try
{
print(); //print() needs to throw the same exception
} catch(Exception e)
{
//handle exception
System.err.println(e.getMessage()+"\n\n"+e.printStackTrace());
}
//finally {
// cleanup here if you like
// }
or this
public void print()
{
for (int i = 0; i < set.size() - 1; i++)
{
try
{
System.out.print(set.lookup(i) + ",");
} catch(Exception e)
{
//handle it here
}
}
System.out.print(set.lookup(set.size()));
}
Do note that using "throws" is kind of a easy way out; it's a cheap delegation that sometimes makes coding easier... if you can, you should try to always use try/catch instead of throws.
Just be aware that whenever you use something with "throws" eventually you will have to put that in a try/catch block and deal with it properly.
Generally to denote improper arguments passed into your method, use IllegalArgumentException which is a RuntimeException and should not be caught.
In this specific case you don't have to write any extra code, the ArrayIndexOutOfBoundsException should take care of improper array access.
Thrown to indicate that an array has been accessed with an illegal
index. The index is either negative or greater than or equal to the
size of the array.