My strongest lead is that the code who deals with the incoming XMLs is actually receiving an invalid/incomplete file hence failing the DOM parsing. Any suggestions?
Incomplete file is definitely the place to start looking. I'd print out the file right before the point you parse it to see what's getting sent to the parser. If it's incomplete it will be obvious. If it's invalid, you'll have a little searching to do.
My first guess would be that the DOM-using code is treating elements that are marked as optional in the DTD as compulsory.
Edited to add:
What I mean is that unless you validate against a DTD, you cannot expect something like the following (example using dom4j) to return anything but null.
doc.selectSingleNode("//some/element/in/a/structure");
The same is of course true if you're stringing element navigation calls together, or generally don't check return values before using them.
You should have a stack trace pointing to where you NPE is thrown. That should narrow down the number of variables that can be null. Rather than getting the debugger or printf out, I suggest adding appropriate checks and throwing an exception where as soon as the error can be detected. It's a good habit to get into to avoid mysterious problems later.
Ideally you should be running your java application inside a debugger, thus when an uncaught exception is thrown you can examine the callstack, variables, etc and see exactly what line caused the crash, and perhaps which data is null that got used.
If you can't use a debugger for whatever reason, then compile your application with debugging support, and add an exception handler for this particular error, and print out the stack trace. Again, this will show exactly what line in what file caused the crash.
Related
I have WindowManager: android.view.WindowLeaked in stacktrace and I have to handle it.
I know reasons why it appears but fixing it will take too much time.
All I need to catch it like typical exception, something like:
try {} catch (WindowLeaked e) {}
But that doesn't work for sure because it's not Exception.
Is there any way to do it?
I don't ask how to fix it or what is WindowLeaked.
The question is: How can I know that WindowLeak happened?
The answer to your question is that your application cannot "know" when it has happened. Despite its unconventional name, android.view.WindowLeaked is a Java exception. However, it is uncatchable because it not thrown in any context where there is no application code on the call stack.
(Apparently, it is not thrown at all. Rather, it seems to be used as a means of capturing a stacktrace for logging. This does seem rather odd since the stack trace doesn't tell you much ... given that there is no application code on it!)
You (the programmer) can know that it has happened (by reading the logcat!) but there is nothing you can do about it ... apart from tracking down the root cause and fixing it.
Window Leak exception usually occurs when the user have open the view and didn't close the view.
quick question. Of course the stack trace gives way more information, but is it a bad practice to use the exception itself instead in some cases? Like just getting "null pointer exception" as opposed to this huge dump of stuff? If this doesn't make any sense, the two differences would be:
(Exception e)
{
print e
}
AND
(Exception e)
{
e.printStackTrace
}
I will say use neither of them in production. You should handle exceptions in other ways, like logging the exception or saving the stacktrace somewhere to review it later and probably display a nice message to the user saying that the app or method failed.
But if you just ask about which of those approaches to use, I will say the latter is better because System.out.println(e) will call Throwable#toString that only provides the message of this exception and maybe you won't get the real cause of the problem.
It depends on the context. Anything that will (or even might accidentally) be presented to the user should not include the stack trace. More than being confusing, you could leak potentially sensitive information.
In my code, I create custom exceptions that have a UserFriendlyMessage property. Friendly messages should be in very plain English. I even have a default catch-all friendly message "There was an unexpected problem. You can try again and if the problem continues contact support".
On the other hand, having the stack trace is invaluable for debugging. In my .NET apps, we go so far as to compile our release code in a special way such that the code is optimized but the symbols are still generated in a separate file. We do this for the sole purpose of ensuring full stack traces with line numbers.
So in summary, display only friendly messages but log (and if you are going to, alert) full stack traces + the friendly message.
The difference between them is that print e returns the type of exception and error message while printStackTrace returns the whole stacktrace of the exception. printStackTrace is more beneficial to be used while debugging.
Example:
print e:
java.lang.IndexOutOfBoundsException
e.printStackTrace():
java.lang.IndexOutOfBoundsException: Index: 8, Size: 0
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.get(ArrayList.java:322)
at com.o2.business.util.Trial.test(CommonUtilsTest.java:866)
printStackTrace might be good for programmer, but it is not readable and user-friendly for end users. As far as I know, printStackTrace prints the results in the default Errorstream: your console. For better practices, you can check the link: http://www.onjava.com/pub/a/onjava/2003/11/19/exceptions.html
I have a Java program that parses several different input files. Even when an error is found in this input files, parsing could still continue and collect several other errors too. So what I want to do is instead of throwing and exception and stopping parsing process, I'd like to register the exception to somewhere, and then continue parsing and collect several other errors in similar way, then in the end I want to check if any errors are reported, and fail or continue depending on this.
Of course I can always do this manually by writing ExceptionRegister or whatever classes but I want to know two things:
1) Is there a problem with this approach? Do you know any alternative designs for what I want to do?
2) Is there a standard way of doing this? (e.g. instead of rolling my own classes I'd like to use built-in functionality if possible)
Thanks
EDIT: I don't know why but someone just removed his answer just before I accepted his answer. Anyway, I think simple data structures should work. Basically, I'll write an exception class that collects several error messages. Then I'll call it's throw method which throws itself if it has at least one error message registered.
EDIT2: Here are more clarifications. My problem has nothing to do with parsing. Parsing was just an example because my program does some parsing. Think this: I'm running an algorithm and in case of an error, I can continue the algorithm to collect more errors so that instead of printing one error and when it's fixed, printing second error, I can print this two errors together.
Exceptions should really be used when you can't handle the input anymore. They are the special case where your code says "I give up, I'm missing some information or I wasn't meant for this". This is a grey area on how to define such cases, but the usual philosophy, as put by Bill Venners in this (old!) article is:
Avoid using exceptions to indicate conditions that can reasonably be
expected as part of the typical functioning of the method.
In your case, it sounds like the content you have to parse might be incorrect, but this is expected by your program and doesn't break enough the contract to stop the parsing. On the other hand, an acceptable exception would be valid to use if an error in the syntax of the input causes the rest of the interpretation to fail, for example.
But people still uses exception because they are quite convenient for stopping execution and going up the stack without going in the tedious details of flowing through returns of results. But on its counterpart, they can have tricky results as you leave some unattended state in some objects.
Your requirements sounds more like a validation pattern is required than one single exception that could cause the processing to stop. One exception to stop all processing: if you throw one, the rest will be ignored. But you suggested that you would collect them instead of throwing those. So I'd say, in that case, why use exceptions at all? It seems you do want to return proper results and not stop the program's execution.
Because if you still go down this path, you could have a collection of exceptions to throw at the end. Which one do you throw? Which one takes precedence, in the Exception collector you created?
Take the example of Eclipse, which has this gigantic platform to handle with a massive collection plug-ins contribution. They use a proper communication channel to log any warning and errors, either in problems pane or through the execution of background task. The latter's execution will usually return an IStatus object or a variant. Based on this IStatus object, the code that receives the status decides to act upon it.
Hence personally, I'd develop a similar object that would collect all necessary user's errors (and not program's errors), that does not break the program's execution and an acceptable part of the contract. This object can contain the severity of the error, its source, a hint on how to fix it (this can be a string, or even a method that contains a pinpointing logic for showing the error or possibly a partial automated fix), etc... Once the execution is done, the parsing's result will get these status objects and act on it. If there are errors, inform the user through the UI and log it as well.
So it's basically the same approach as you initially suggested, minus the exceptions and minus the commodity of jumping through the stack that could lead to nasty side-effects and very difficult to debug errors.
I think I understand now. What you are actually trying to do is to collect the parse errors (which you are representing as exceptions) and continue parsing the current input file.
There is no standard way to do this:
The "exception register" is really nothing more than a list of parse error descriptors ... presumably some parser exception. If you can catch the exception at the appropriate point, it is trivial to add it to the "register".
The difficult part is the functionality you are not talking about:
How to capture the location of the error
How to get the parser to continue parsing when it gets a parser error.
The solutions to these depend on how you have implemented your parser.
If you are using a parser generator, there is a good chance that the PGS documentation explains how to implement this.
If you are implementing the parser by hand, you will need to roll your own code to track error locations and do syntax error recovery.
Basically, I'll write an exception class that collects several error messages. Then I'll call it's throw method which throws itself if it has at least one error message registered.
That sounds like an abuse of exceptions. A better idea is to accumulate the errors in a list, and then create / throw the exception if the list is non-empty. Use a static method in a helper class if you want to avoid duplicating code.
An exception that conditionally throws itself is (IMO) bizarre! And creating lots of exceptions that you are unlikely to throw is likely to be inefficient. (Depending on the JVM, the expensive part of exceptions is often creating the exception and capturing the stack frames. The expense can be significant.)
So this might be a dumb question but I don't know what to ask for since 'jruby print stack trace' googled doesn't come up with much thats worthwhile but,
How does one print the stack trace when writing Jruby code that accesses Java classes that throw exceptions? ie right now I took code from someone else that looks like
rescue JavaSql::SQLException
puts "SQLException"
end
which works, but I'd like to see which particular SQLException is happening like I would in Java (ie. PrintStackTrace(Exception e))? How does one accomplish this?
I've never worked with Java exceptions in Ruby, but AFAIK, Java exceptions get presented to you as Ruby exceptions, which means you can get the exception message by sending the :message message to the exception object:
begin
# stuff
rescue JavaSql::SQLException => e
puts "#{e.class}: #{e.message}"
end
Is that what you mean? I'm not quite sure what you would need the stacktrace for in this particular situation, so I probably misunderstood.
One would imagine it relies on the underlying implementation. If the underlying implementation just swallows the exception you will not be able to see a stack trace. Also why don't you just allow the exception to bubble up in your ruby code so that the trace gets thrown out to the screen?
Would it be useful to include the class name and variable name in any NullPointerException message? I know that it might not always be possible because of changes made by a JIT but is seems like the info should be available often (class members, etc).
From: http://jamesjava.blogspot.com/2005/04/what-was-null.html
That depends. If you get the stack trace, it is clear what class threw the exception. This usually leads to making sure your environment will give you stack traces when there are unhanded exceptions.
Providing as much information as possible during errors is a good thing... Right?
Helps out tracking the bugs.
Edit: (Yes)
No, I don't think that this would at all be "useful".
Instead, you should watch out not to throw NPEs in the first place. Checking your values before you use them (null validation) and the likes. This should happen before you call a library method and after you get back a result (iff the API specifies that the method may return null. Of course, sometimes it will do so anyways, but then that's a bug).
If you think that NPEs should carry this information for debugging, think again. That's what debuggers are good for. An exception is simply there to inform you that something has gone wrong. Remember that unchecked exceptions occur at runtime - and have to be generated there. In order for the Exception to know which variable contained null, the byte code would have to know about variable names. You don't want to bloat your byte code with stuff like this. The class name is contained in every logging output I recieve from my programs. That's what logging is good for.
Java already eases the debugging process a lot by giving you the line number and full stack trace. C programs fail with Segmentation fault. You have to use strace or a debugger in order to even get so much information.
Note that javac does include a compile time option to include source file information at compile time, but this is intended to be used by a debugger, not the random Exceptions that get thrown. Quoting Sun's javac man page:
-g Generate all debugging information, including local variables.
By default, only line number and source file information is
generated.
-g:none
Do not generate any debugging information.
-g:{keyword list}
Generate only some kinds of debugging information, specified
by a comma separated list of keywords. Valid keywords are:
source
Source file debugging information
lines
Line number debugging information
vars
Local variable debugging information
Long story short: use a debugger.
Yes, that would be useful. Especially if you have a mechanism where the error message (exception.getMessage()) is displayed on-screen but the actual stacktrace gets hidden away in log files which you can't access immediately.
Are you throwing NullPointerException? I think you should probably do null validation in the code.
I would also consider using open source logging tools like Log4J.