I've come across some really strange behaviour in my Java code. There is a exception shown on my Eclipse log console saying Exception:java.lang.NullPointerException with no reference to the code where it occurred.
On debugging I found out a line where this occurred and so put it in try-catch hoping I catch it. However it didn't return in catch block.
The strange part being even though there's exception thrown at the line immediately after it executes and the execution continues normally.
Can some one please tell me the probable cause?
I could have attached the source code but I have checked the parameters and all seem fine.
My main reason for this post is to learn about such behavior if any of you coders ever came across.
Probably a problem with Eclipse. I have seen that behaviour before, and restarting Eclipse solved the problem.
Please check whether your builder is activated and the changed source code is build automatically. Otherwise your code changes will never get it into your runtime application.
I am pretty sure, that the executed source code is different to the source code shown in your editor.
If you see the exception's message but no stack trace, that is caused by code that looks like this:
try
{
// something which causes the exception
}
catch (final Exception err)
{
System.out.println(err);
}
The problem with this code is that it only prints the result of the exception's .toString() method. For most exceptions this is just the exception class and the message. This code omits the stack trace, thus making it much harder to debug the problem.
If the exception is to be caught, then change the code to look like this for the stack trace to be included in the output:
try
{
// something which causes the exception
}
catch (final Exception err)
{
err.printStackTrace();
}
Related
I work on a Java application that makes fairly heavy use of Javascript to form the business logic/glue. It runs using Graal. This all works fine, but we struggle with effective error handling.
This is essentially how the JS is executed:
try {
Context context = Context.newBuilder("js").allowAllAccess(true).build()
Source s = Source.newBuilder("js", src, "script").build();
context.eval(s);
} catch (Exception e) {
LOGGER.error("Exception occurred in JavaScript:...", e);
}
So when errors happen we log them somewhere so we can do some postmortem, etc. It's possible to get the JS stack trace in these logs out of the PolyglotException that Graal throws, which is great. However, things are more complicated when some JS code has called back into Java-land, and a Java exception has been thrown:
var x = callJavaFunction("invalid parameter"); // Throws a NoSuchElementException, for example
The PolyglotException has an asHostException() method that returns the original Java-land exception, and my code that executes the JS files is smart enough to understand this and produce a useful error log. The problem arises when the JS code has tried to catch this itself, for whatever reason:
try {
var x = callJavaFunction("invalid parameter"); // NoSuchElementException
} catch (e) {
doSomeCleanup();
throw e;
}
Now we have lost the original Exception, and even worse, the JS-stack trace now just shows us the catch block, instead of where the cause was. isHostException() returns false, because this is just a JS error now. I cannot find a way to get at the original cause, which makes diagnosing errors quite difficult, especially when they have come out of a production system. The original Java exception message ends up in the JS-error object, which is helpful, but we don't have the stack trace, which is not.
What approaches can I take to try and address this?
One thought I had: Can I hook into the GraalVM and get a callback whenever a host-exception is thrown? At least that way I could have a log saying "the following Java Exceptions were thrown during execution" which I could attach to the error report. So far I've not been able to find a way to achieve this.
I found a really weird bug within my Java Code
Even when i force a RuntimeException in my program it is not recognized by the JVM.
Here a demo of what I have written
private static void someMethod(){
//Some Code
if(true)
throw new RuntimeException();
// More Code
}
I added the if(true) to prevent the unreachable code message, just for testing.
But I think that the real problem is that there is some unhandled Exception in my code, which I cant really log, because the printStackTrace() is missing, or else i should get a console log.
Also I get the plain text: Exception while removing reference.
But its no System.err message, it just look like System.out
Are there any other methods of logging exception, excpect the default console, and what could cause a exception to be unhandled?
NOTE: I use following external libraries: JNativeHook, JLayer, Apache Commons IO
Full GitHub repo
The Exception should occur in CsgoSounds.java at line 944
OS: Windows 10, jre version: 1.8.0_60
There are checked Exceptions and unchecked ones (everything that extends runtime exception).
The compiler force you to deal with checked exceptions (with a try catch or a throws declaration). You are not forced to deal with Unchecked exceptions. But you can, just add a try catch around your code, then you can call printstacktrace on it.
JNativeHook was blocking all console outputs. I had to enable the function first.
Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
logger.setLevel(Level.WARNING);
did the job.
I am quite new to Java and stumbled upon an problem, I can't understand (I am using Eclipse Luna for developing and executing):
I call a method that might throw an error and surrounded it with a try-catch-block:
try {
transaction.execute();
} catch (ModbusIOException e) {
log.debug("Fehler bei Modbustransaction: ModbusIOException - " + e.getMessage());
e.printStackTrace();
} ... // more catches
The execute-method actually throws the ModbusIOException - but it is not caught in the catch-block. In the console I got the following output:
net.wimpi.modbus.ModbusIOException: Read failed
at net.wimpi.modbus.io.ModbusTCPTransport.readResponse(ModbusTCPTransport.java:180)
at net.wimpi.modbus.io.ModbusTCPTransaction.execute(ModbusTCPTransaction.java:193)
at de.vksys.modbusclient.ModbusClient.getPlantState(ModbusClient.java:121)
at de.vksys.modbusclient.ReconnectingModbusClient.main(ReconnectingModbusClient.java:36)
If I click at the line with getPlantState Eclipse marks the line in the try-block above. But why isn't it caught there? I also checked the full name of the ModbusIOException in the catch block and is the same ... net.wimpi.modbus.ModbusIOException.
Any idea, what might be the reason? If you need more code to track this down, just tell me.
Thanks in advance,
Frank
It indeed caught the exception. You just printed the stack trace and that's what you see in the standard output.
Catching an exception, doesn't mean that it wont maintain the stack trace and handling exception means that you need to code it so you could recover from the exception (which is what has happened in your case else your program would have went to the parent method which called your method rolling back the stack i.e. in readResponse method) where you might say ok things happen or you rethrow the exception. for e.g. given a code as below:
void myMethod() {
try {
methodThatThrowsIOException();
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("I will be printed");
If you didn't caught the exception, then you would never have executed print statement like "I will be printed"
}
I'm trying to catch an "android.database.sqlite.SQLiteException: error code 5: database is locked" exception with:
try {
db.insert("mytable", null, myvalues);
} catch(SQLiteException e) {
Log.d("My App", "caught");
...
}
For some reason, I still get the error, and "caught" doesn't show up in LogCat. I tried catching a general "exception", but that still doesn't work. What's wrong?
UPDATE
I found the issue, and it is really weird: for some reason changing db.insert() to db.insertOrThrow() as goto10 stated magically fixed everything. The error was comming from that line, but maybe it wasn't throwing an exception and only crashing or something?
I don't believe that .insert will throw an exception. You're probably just seeing a log message that's being written by it when it catches the exception internally. If you want it to throw an exception when an insert fails, use .insertOrThrow instead.
Try this
try {
} catch( SQLiteException e) {
Log.e("My App",e.toString(), e);
}
If that catch block is failing to catch the exception then either it isn't being thrown inside that particular try block, or you've got the wrong exception. The fact that it still doesn't work if you catch Exception says that it is the former problem.
So you need to find out where the exception is really being throw. I'd try changing the logging configurations to get LogCat to log full exception stacktrace. That should tell you where it was thrown. If you can't do that, then you'll need to find this using a debugger ... or by trawling through your applications source code to find where the exception is being logged.
(The other possibility is that the catch block is catching the exception, but you've got your logging configs set up to discard "debug" log events.)
The exception is probably thrown when you open the database, not when you insert a new row.
I'm using NetBeans as my IDE for developing Android.
However, when I get an exception, Netbeans does not break on the exception as I expect it to.
I have checked the box "Stop on uncaught exceptions" that can be found in Options --> Java Debugger --> Stop on uncaught exceptions but that doesn't help.
Furthermore, where can I see the actual exception message? I don't see anything. I have no clue where and when an exception occurs, just that it does occur.
I've read some on the netbeans.org site about a bug in 6.9.1 that was fixed, but it doesn't seem to be fixed in 7.0 that I have.
The debugging window doesn't say anything useful at all, gives some form of stack trace that is pointless as it doesn't specify any of my own code.
I switched from Eclipse because that IDE sucks, NetBeans is much leaner, but the debugging needs to be fixed to be useful.
I have this problem when I use netbeans too. To get the exception message, I use try-and-catch. In the catch() statement, call a function that contains some code and put a breakpoint on it. Then when the exception is given your breakpoint in the catch statement will be called and you can read the information (error message, stack, etc.) from the Exception obect.
try
{
// Doing something here
}
catch (Exception e1)
{
// This is called when an exception occurs
doSomething(); /// Put breakpoint here
}
UPDATE:
I am not sure if this will work for android but you could try entering a "New Breakpoint". When entering a new breakpoint to break on an exception, you need to know the
exact package/class exception name. For example, if you want to catch a
NullPointerException, then you go to Debug >> New Breakpoint to create a New Breakpoint and enter
java.lang.NullPointerException into the Exception Class Name field in the
Breakpoint Properties dialog. Choose whether to break on caught, uncaught or both, exceptions and it will hit a breakpoint if that type of exception ever occurs in the class/project.
I had such behavior where I had my source file that generated the exception NOT in "default package". When I moved everything to "default package" it started working fine and stop on exception automatically.
This answer actually also answers this question:
https://stackoverflow.com/a/2671390/415551
To quote user Finbarr:
Go to debug > New Breakpoint (alternatively CTRL+SHIFT+F8). Change the
breakpoint type to Exception in the top right hand drop down menu.
Type java.lang.NullPointerException in the Exception class field.
Choose whether to break on caught, uncaught or both.
Debug your code and watch the glorious auto breakpoint when the
Exception is thrown.
Simply change java.lang.NullPointerException to java.lang.Exception to break on any error.