I have a legacy java app written up by a previous developer. A bug has recently been found in it, and I've been given the task of fixing it.
Part of the problem is that there were never any error messages reporting from it.
By putting in a lot of logging messages, I finally narrowed it down to a specific line in the code - it's trying to run a method on a null object.
This is something that SHOULD have thrown an error into the log. Yet it hasn't. And even fixing this one, there's a lot of this problem in the code - assuming something will have a value when it doesn't. Every time I put in a data-verification for one, it fails somewhere shortly down the line for a very similar reason, and then I have to go through the hassle of putting in logging commands every other line again to finally narrow it down.
Why would a java program be silently failing instead of throwing errors? I can't seem to find any sort of setting suggesting that this is on purpose, but I'm really not even sure where to look for such a thing.
Related
I'm modifying a java program to search through a specific folder and load plug-ins at runtime. The plugin code is working fine. I have created an UncaughtExceptionHandler to catch problems with plugins that weren't coded properly, and for the most part that works. Except for one issue (one so far, anyway):
The plugins need to have a class that implements a specific interface, so that the main program recognises them as plugins. If the developer misses one of the abstract methods, an AbstractMethodError gets thrown. It goes through my ExceptionHandler and I'm able to put up a message to the user indicating that there's a problem with the plugin. After that, though, the program just hangs. What I want is the program to continue going so that I can skip the rest of the plugin stuff, remove it from the plugin list, and let the user run the main program without it. I put a try/catch block directly around the call to the missing method, but the catch doesn't get executed. It just goes to the ExceptionHandler and then... I don't know where it goes.
This is my first attempt at exception handling so I'm sure I'm just missing something obvious. Any help would be greatly appreciated. Thanks so much.
The problem with exceptions that sub-class from the Error class is that most of them are not recoverable (in your case it's AbstractMethodError). As per the Error class java-doc:
An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it.
I.e. it's not guaranteed that the app is recoverable after an Error is thrown. Depending on how you load/execute that plugin there might be some workarounds. First of all, you could check the loaded plugin class via reflection (some examples) if there is an implementation of the needed methods before actually trying the exectuion - so you could catch/throw an Exception rather than get the Error and hang later.
If it's not an option, you could investigate further on what is actually hanging after getting that error by analyzing thread dump re
Taking thread dumps in production
I am working on a spring-shell application, my #CliCommand methods have custom logic that ends with responses like SUCCESS / FAILURE.
I saw that it is possible to modify the spring-shell exit code by throwing an exception (it becomes 1).
In case of FAILURE I would like to return an exit code different from 0. Is it possible to do that without throwing an exception?
This is not currently possible without modifying the Bootstrap/ExitShellRequest classes.
Keep in mind that Spring Shell is first and foremost meant to create interactive applications, hence the lesser emphasis on system exit codes. If however you feel this should be a supported feature, please open a ticket for it.
Lastly, the System.exit(x) solution may work for you inside your own commands. Be wary though, that the whole shell context may not clean properly, which may be a problem.
can it maybe??
System.exit(1);
That is my question. More specifically, I'm trying to get used to Eclipse's debugger and I'd like to know if printing to console is still done in some cases or if it's considered a bad practise that should be entirely avoided. Also, what can be considered as good approach(es) to debugging overall?
Use System.err.println() instead.
Why?
System.out.println() is often redirected to a file or another output, while this is pretty much always printed on the console. It's easier for debugging and also the right way to do it.
Edit (warning: subjective):
Since you asked about whether System.out.println should be entirely avoided: I don't believe in anything that you must always avoid, be it using goto's, crashing your computer with a BSOD, or whatever. Sometimes you just need a quick-and-dirty way to get small things done fast, and it just plain isn't worth the 1 hour you'll spend on it to try to do things the "right" way, instead of a 5-minute fix, no matter how good the "good" way is. Use your judgment when deciding if something should be used or not, but never set rules for yourself like "I'll never use goto!". :)
Edit 2 (example):
Let's say you're debugging a crashing driver and you suspect that an if statement that shouldn't be execute is being executed. Instead of spending three hours finding out how to use ZwRaiseHardError to display a message box, just call KeBugCheck inside the if and crash the darned system. Sure, you'll reboot, but unless your reboot takes hours, you just saved yourself that much time.
The best choice would be a logging library (of course, this adds an extra dependency to your project). Check out commons-logging, for instance.
The main advantage is that you can write your debug messages in the DEBUG level and when you deploy your code, you'll just configure the logger to skip those messages (instead of searching for all occurrences of System.out.println in your code).
One other great advantage is that loggers usually can be configured to write anywhere (even send email messages or SMS) also without touching your code.
Minor point: if your program actually outputs something useful to the console via System.out, you may want to instead print the debugging info to System.err
You should generally strive to have as much debugging as possible (ideally using some standard logger like log4j). This both eases debugging when you're actually developing the program AND allows for much easier debugging of already-released code in production. The benefit is that your code remains unchanged and you don't need to ADD debugf prints, yet by default the logging config can turn off the logging until it's actually needed (or at least turn down the level of logs)
As far as general simple "throw printlns at the wall" debugging, it can sometimes be one of the fastest ways to debug, though it should by no means be the only/main one.
Why can it be useful? Among other reasons, because running a Java program in a debugger may be much slower than outside of it; or because your bug manifests in an environment/situation that can't be easily replicated in your Eclipse debugger.
If the debugging print lines are not going to stay in the code after you've fixed your bug, then do whatever is easiest for you. Lambert's advice of using System.err.println() is a good idea since you can differentiate it from other output that your program may produce. If the debugging print lines are going to stay in your code, then I would advise on using a logging framework like log4j. This way you can dial up or down the level of output based on whether you're trying to debug something or just running in production. Be sure to output things at the right level when using log4j. Don't just log everything at INFO.
I use System.out.println for my debugging in case i have a problem or to inform me that methods have started to make sure everything has worked properly but when I publish the program I always remove it because it slows down the program.
I'm getting the following NullPointerException while trying to use the Play FBConnect module:
Caused by: java.lang.NullPointerException
at tags.fbconnect.FBConnectTags._button(FBConnectTags.java:26)
at tags.fbconnect.FBConnectTags$_button.call(Unknown Source)
at /app/views/main.html.(line:17)
at play.templates.GroovyTemplate.render(GroovyTemplate.java:203)
This seems to be the line where its occurring: https://github.com/rbamba/play-fbconnect/blob/master/app/tags/fbconnect/FBConnectTags.java#L26
Unfortunately I'm not sufficiently familiar with Play modules to debug this myself.
edit: In response to a comment, I believe the fbconnect module is correctly configured, since this is being reported earlier in the log:
13:12:13,225 INFO ~ Module fbconnect is available (/home/****/play-1.1.1/modules/fbconnect-0.3)
edit2: I've actually got it to progress past this point on my local machine, but still getting this NPE on my production server.
I can't see anything specifically wrong with the plugin code. To explain a little of what is going on,
// the line of code with the error
String url = Play.plugin(FBConnectPlugin.class).session().getLoginUrl(scope);
Lets break this down a little
Play.plugin(FBConnectPlugin.class)
This line asks Play to return the initialised plugin, from the list of plugins configured within Play. If the Plugin is not set up, then it returns null. This is the most likely reason for the error.
.session()
This simply gets the session object from the FBConnectPlugin, which is a statically created object, so will not be null.
.getLoginUrl(scope);
This builds the URL up. This method is not called, otherwise you would see it in the stack trace.
Therefore, the problem is that you have not configured the plugin correctly. Check over the documentation again to make sure why it has a problem. Alternatively, you may want to check out the FbGraph module. I installed this a few days ago, and have a Facebook app up and running already. It is very simple, and the documentation is excellent.
The answer is a little long-winded, but as you said you did not understand how modules worked, I thought it was worth explaining.
I spoke to Regis Bamba, one of the programmers who works on fb-connect.
I eventually decided to use the fbgraph module instead, and I'd probably recommend this to anyone thinking of using fb-connect because its more powerful, and seems to be better maintained. Even Regis recommended using it :-)
Regardless, here is what Regis suggested to get rid of the "java.net.URISyntaxException":
The solution is to manually replacing it with its encoded value, before encoding the whole string.
The getAuthUrl() function in FBConnectSession.java should be:
public String getAuthUrl(String authCode){
return "https://graph.facebook.com/oauth/access_token?client_id=" +
WS.encode(id)+"&redirect_uri=" +
WS.encode(Router.getFullUrl("FBConnect.callback")) +
"&client_secret="+WS.encode(secret)+"&code="+WS.encode(authCode.replace("|","%7C"));
}
I'm running Eclipse for Java. I created a DOM version of an XML file. Now I want to change an attribute of an element in the file. I called a method that called a method in the class that controls the DOM, and I got a dialog box saying "JDI Thread Evaluations has encountered a problem. Exception processing async thread queue" while debugging.
I'm a relative newbie at Java and have not come across such an error, and I have no idea what's causing it.
If anyone has any suggestions as to the cause of the problem and/or ways to fix it ...
Thanks so much!
Keep an eye on your "Watch" expressions - if you don't need them, remove them all. Sometimes certain watch expressions have caused this error message for me.
This might also explain why it happens to intermittently for people (sometimes they have watch assignments that cause the error, however restarting or removing the right watch can solve the issue without them knowing it.)
The Java Debug Interface (JDI) is part of the Java Platform Debugger Architecture. One apparent way to trigger this exception occurs when an object's toString() method carelessly returns null. You might want to try a different debugger, and it wouldn't hurt to validate your XML. As noted in comments, the problem may appear intermittently, suggesting a thread synchronization problem.
This error occurs quiet a few times when you debugging.
You can clean this up by removing all watch statements and all breakpoints and restarting Eclipse.
The problem can also occur if source lookup is incorrectly configured. For example lets say one wants to watch the expression foo.bar(). Now if source lookup is incorrectly configured, the debugger is unable to resolve the binding for expression foo (see this eclipse bug). Then the invocation of .bar() will fail with a NullPointerException.
This problem may occur if you have "Detail Formatters" configured for specific classes (in Eclipse: Java -> Debug -> Detail Formatters). Try to disable them.
This was replicated in eclipse when I was debugging the expression which reads: "", which is just an empty expression.
So, if you're getting this problem, one solution may be to check to see if one of your expressions is empty or similar, then aptly delete it.