I used abort() In C to make my program crash. And debugger will trap this.
Maybe equivalent in Java should be exception. But Java also has very strict exception chaining policy, so using of exception for debugging purpose doesn't seem to be a good idea.
What should I use for this in Java? Intentional program crash for debugging purpose which can be trapped by debugger. (I am using Eclipse)
Update
It would be very nice if the code can be optionally opt-out on release build.
In Eclipse you can set debug points, and run in debug mode.
That said, there is a difference between a CheckedException (which must be caught by the calling function or passed up the chain) and an UncheckedException (which is closer to what you want). Throw the latter if you want to force a crash.
However, this is generally a bad way to program. You'll find better results using alternative means to catch the errors you want.
You can use assert(false). Assuming you're using Eclipse for the debugger, you can set Eclipse to break on specific exceptions (in this case, AssertionError). Make sure you enable assertions, otherwise it won't do anything.
Since you have to explicitly tell the JVM to enable assertions, I think this would count as "code [that] can be optionally opt-out on release build."
I do not know how to handle it in Eclipse. However, under JDB, this can be done by catching the Exceptions. Eclipse should have such an interface.
Using command line like this
"catch java.io.FileNotFoundException"
For details, please refer to here
Related
I'm assuming that the reason the assert statement throws an AssertionError to stop your program is because an assumption about your code is wrong. The problem is, how am I supposed to debug my code by using debugging tools when the assert statement kills my java process?
EDIT: My question is different because the answer to the supposedly duplicate question doesn't answer mine.
EDIT:
If you look for a way to throw an exception and not throw an exception at the same time, there is no solution for this.
In modern IDEs you can, during debug:
tell the IDE to block on any AssertionError without setting any breakpoint
change the code of a method during a test when blocked, such as commenting out an assert
tell the IDE to resume running a method again How to step back in Eclipse debugger?
Also assert can be disabled for the purpose of debugging. That's one reason to use an assert instead of an if-block.
See:
How do I disable Java assertions for a junit test in the code
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
My question is from the perspective of language design.
Why is assert treated differently i.e. it raises a error and not an exception, it is not enabled by default etc..
It does seem elegant(very subjective opinion), easy to read(again subjective) for doing validations & also there are tools(IDE) which can live-evaluate it and provide warnings based on assertions.
I'd say that the reason is that defaults for Java are meant for production code (the "release" version of software) - if users need to build your code they will use provided defaults and if you are developer and want to have better reporting you can always make some additional effort.
Usually you don't want to ship assertions with a release version. Why? You can always design your code to perform some not disturbing background error handling and throwing AssertionError in users face is not always the way to go.
Most of the time I see them used as additional code testing - when you run regression tests and code coverage is high no assertion error suggest that there are no (obvious to spot) errors in your code. If some happens, you can deduce from stack trace what went wrong and why. On the other hand clients shouldn't be bothered with seeing descriptive error information.
So how should you actually use them? In my experience you should design code to not use assertions to perform error handling. If you want exception to be thrown somewhere throw it explicitly yourself. Once code can handle itself, you can add assertions to check pre- and postconditions as well as invariants - so basically used them to check algorithm correctness instead of data correctness. It has value for developers rather than users. Once you have enough confidence in your solution, you can disable assertions, your program still works fine and your users don't have to run program with additional runtime overhead.
Asserts are tools for the developer.
The core reason it's not enabled by default is that assertions via assert are not meant to provide run-time validation/protection for production code.
assert is a tool for use in development process and during testing that should not impact performance during actual running in production environment.
Imagine a very heavy weight assertions that are critical to check when building out a new feature or a change against a entire range of allowable inputs, but once built and properly tested, don't need to run until code changes again.
It raises an error, because the severity of an assertion violation is high enough to do so.
An example for an Exception is something like ArrayIndexOutOfBounds. This might be reasonable in some cases and you might even expect (and handle) such a case.
But an assertion violation is (like out of memory e.g.) nothing you would ever expect or you would like to deal with. It's an error and there is no excuse.
Assertions are not enabled by default, because they should be always fullfilled. You enable them to test for that, but then you "know" (as far as you can know) that they are not violated. So you don't need to check the conditions (which might be performance intensive) every time in production code.
The good thing about assertions in Java is, that the code actually performing the checks is never executed, when assertions are not enabled.
For example:
if (!doComplexChecks()) throw new AssertionError("Damn!");
might take a lot of time and you want to verify this when unit testing or debugging, but in production you just don't want that.
But this code
assert doComplexChecks();
is only executed, when assertions are enabled, so it saves you a lot of time in production code.
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.
Do I have to take a look at the java api everytime I instantiate an object / call a method from a class in it? Also, do I always have to know which classes are in the java api and which are not?
If the exception is checked, then the java compiler will force your invoking method to either catch the exception or declare that it could throw the exception.
If the exception that is thrown inherits from Error or RuntimeException - I.e. is unchecked, then you have no way of knowing besides javadoc and looking at the code.
A good example of the latter, is NumberFormatException, thrown by Double.parseDouble(String). The only way to know is that the javadoc tells you it could throw this exception.
Modern IDEs (Eclipse, Netbeans, IntelliJ etc) provide easy access to this documentation.
I use Eclipse IDE which will make sure you account for all thrown exceptions. I highly recommend it.
http://www.eclipse.org
Knowing what exceptions a function throw is not different from knowing what arguments it needs, and what type it returns.
You either know it, look it up, or use an IDE that does this for you. BTW for checked exceptions you will get a compile-time error, so that can also be an option.
For you second question, In general...
Packages that start with "java." or "javax." are in the J2SE API.
Most packages starting with a internet domain prefix like "com." or "org." are supplied by third parties. Don't count on com.sun being stable though.
Packages with none of prefixes the above are likely not following the package naming guidelines or predate them.