I have a project in which certain data has invariants which are not enforceable using language constructs, but I've intended to write my code such that they are maintained. If they are for some reason broken, it means that my code is buggy. I have some sanity check code which can discover if these invariants have been broken, but I'm not sure what is the canonical Java approach to responding to such a condition - is there some standard exception that I should throw? Use an assert?
Note that this is an issue of a value being set incorrectly at some point. The error itself does not occur at the time of the sanity check, but rather it occurred in the past, and the sanity check is just now discovering it (ie, it's not bad that the sanity check itself is running, it's just bad that the check failed).
Thanks!
Throw an IllegalStateException. It is meant specifically for purposes like this.
Deciding how your application would react to a broken invariant would be a sensible first step
In case a broken invariant is unrecoverable and basically means a bug a code, i second an answer about IllegalStateException.html (you may want to add some useful context for debug purposes ,e.g. variables in broken invariant) - such unchecked exception would stop a running thread
In case you can recover from broken invariant (by replacing some arguments with sensible default, giving it a second try) - you may want to throw a checked exception and catch it on one of upper layers and execute plan B
Related
I am using Android Studio (intelliJ-idea) for Android development. I get a warning for this piece of code:
if (status == STATUS_SOLVING) {
if (!solverThread.isAlive())
if (status != STATUS_SOLVED) // <<<<<< WARNING THIS LINE
status = STATUS_DATA_COLLECTING;
}
The line indicated above gives me a warning, saying that this condition is always true. I can see why this is true if the whole program runs on a single thread.
But since my program uses a parallel thread to change the value of status, does it not mean that this condition might change between line #1 and #3 in the snippet above?
Is this a valid warning? Am I missing something?
Do things change if I change the nested ifs into one single if with && operator?
It means that if you're counting on a value being changed by another thread that's a dangerous programming tactic and that the compiler won't know that its being accessed by different friends and will optimize assuming it isn't.
Any variable that may be touched by multiple threads like that needs to be declared volatile to inform the compiler that its touched by multiple threads, and special care needs to be taken in treating it. If you didn't know that I'll bet you have a dozen other multithreading bugs waiting to happen.
If a second thread is involved and changes status then certainly the value can change between lines 1 and 3. Especially since you don't seem to have any kind of thread synchronization in place, deliberate or not.
Granted, the code seems a bit unsafe, because you would not normally have two threads accessing the same variable without some kind of concurrency control. But this is speculation since I don't see the rest of your code.
Anyway, this is a warning, not an error. Sometimes warnings are wrong, that's why they can be suppressed.
You could see this as a sign that you're up to some unsafe stuff though. Perhaps you could post some more code in case you want to discuss the actual synchronization aspects?
Does java has library exception class which means actually not an error, but good termination? I know I can make my own class or use null, but wish to know.
EDIT 1
I want to use exception object as an old fashion return code for a method, so I need something equivalent to ERROR_SUCCESS code in Win32 API.
Exceptions in Java are meant to be used for abnormal termination only. Using them to flag correct termination should be considered really bad practice.
You might use return values instead.
To directly answer your question: No. There is no standard Java exception that means "this is a normal termination".
If you wanted to, you could define a custom exception that meant this for your application.
However,
... using an exception for "normal control flow" goes against the strong recommendations of the Java designers, and a Java "Best Practice" rule that has pretty much universal acceptance. This is not to say you should NEVER do this. It is just that the cases where it is justifiable to do this are VERY RARE. (And you'd need to take special steps to avoid grossly inefficient code ... )
Anyway, the fact that it is (almost) always a terrible idea to use exceptions for normal flow control explains why a standard exception was never created. The Java designers clearly didn't want to appear to be encouraging this practice.
The closest thing to a "good termination" signal I can think of is not an exception, but a call to System.exit(int) with 0 as argument, to indicate to the operating system that the program ended successfully. From the javadocs:
Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination. This method calls the exit method in class Runtime. This method never returns normally.
As has been pointed out, an exception is not to be used to inform of a "good termination", quite the contrary.
No. Exception means exceptional situation. You should structure your program flow so that exceptions are thrown only for exceptional situations, rather than on the normal flow.
So, if you want to return "success": return true or some enum Result.SUCCESS.
Exceptions are mean to denote that something went wrong. Different exceptions depict different items which went wrong and will thus cause the program to terminate if not handled. Something successfully finishing is not an exception.
I think what you need to do is to either return a particular value, or else, make your application fire some sort of event. In this case throwing exception is not (at least for me) recommended.
Depends what you define as "good termination" I guess - is a security exception good because it stopped someone from hacking your system? It's not really an error, but it is an abnormal situation that you need to handle.
In general exceptions are designed to be used for exceptional conditions only (which may or may not be an error in your code - it could mean that some resource is unavailable, or a security check failed etc.)
If you are using exceptions for regular control flow (i.e. they are getting thrown in normal, expected circumstances) then you are probably doing something wrong.
Maybe you mean an InterrupedException? This one is thrown, when you wish to terminate a thread gracefully.
As some other responses said, when there is no exception, nothing is raised.
Therefore, you can just your code for the "no-exception" into the try block after the rest of instructions. Something like:
try{
//code here
//code of no exception
}catch(Exception e){
//nothing or exception code
}
or you can just create your own exception by doing a class that extends Exception
I've got a decently complex little game going on in Java (solitaire, essentially like the Windows version), but I have yet to do very much error handling.
Almost all of the methods across my classes will end up either getting called by an initial constructor (eventually main()), a paintComponent() method, or a mouse event. So, my question is, is it bad practice to just use "throws Exception" on all of my lower-level methods, and only do a try/catch at my top-level methods to catch ALL the errors at once? (e.g. 3 try/catches - one for the painting, one for mouse events, one for the main method).
I realize this prevents me from easily dealing with errors on-the-spot, but I don't really plan on doing that anyways. My error handling is going to consist of writing to a log, telling the user, and killing the program. Keeping this in mind, is there anything bad with doing my error handling this way?
It depends on how you want to approach the situation.
If you just want to catch any possible exception and you don't mind about the handler code, you could simply use "throws exception", and there's nothing BAD with it either. It's like a try-catch block that covers all the function.
If you want to write specific code for specific exceptions, you should use try-catch blocks to write appropriate code for each handler.
Based on what you're saying, any caught exception would just notify the user and exit the application. Well, in this case you could just use the first approach. It's not necessarily the BEST approach, and neither is killing the application, however, if that's your strategy you could just use "throws" for each function.
Hope that helps!
If that's all you wan't to do in a case of an error, then it makes perfect sense to do it that way. This eliminates code duplication and scattering of related code. However, if you're thinking of changing how things work in the future (if there's a possibility of this happening), I would suggest to try and push the catch down as far as possible (maybe even eliminating the need for exceptions at all and just logging and exiting right away).
If you use the exception's inner fields (specifically message, which you can set in construction time), you can even eliminate the need for 3 different catch blocks and just use one (depending on your actual actions in case of an error, of course).
I wouldn't - the big reason being that it breaks encapsulation. The reason why this is important in this case is that your error handling code has one of two futures:
Becoming enormous to handle in an informative way every error the program can throw.
Be tiny but not helpful at all: "Some error occurred somewhere".
To my mind, the best structure is to catch the error, log it, alert the user, and exit as far down as possible. There's nothing that says your mouse handling code can't exit, right?
In fact, I would create an error handler class that you can call from just about anywhere, and it handles the notification and logging. Then your exception handlers can just populate it with the message to display/log, and all other code is shared. It will cost you less typing to delegate to this class than adding throws Exception at the end of every function everywhere.
If you must have a top level handler, it should just catch any unexpected runtime errors, so that you can log it and show the user that the program is really quitting for an error, and not just dump to the desktop. All other errors - even if you just want to bail out - should be caught as close to "where the exception has meaning" as possible.
I do the same thing as you are describing most of the time. What you're basically doing is working around the stupid checked exceptions that Java has. It shouldn't even be necessary to add 'throws Exception' everywhere.
If I'm working on an API that other users will use I may create specific exceptions to show what is going on in case they want to handle different exceptions in different ways.
If an error is severe enough to always exit the program, you may be better of throwing a RuntimeException instead. They are used to indicate unrecoverable errors and will avoid problems with putting "throws Exception" everywhere. You should have a handler for RuntimeExceptions anyway to provide a user-friendly error report in case they happen.
If you throw checked exceptions, they should be as specific as possible. Throwing and catching Exception can hide other exceptions that are thrown (including RuntimeExceptions) that you didn't intend and could have been handled differently. If you want to throw a general exception, you can always create your own exception class and throw that instead.
The exception handling can depend on the context so there's not one way to handle everything. If the user clicks a button to open a file and there's an error reading it, then it would be ok to throw an IOException up to the UI layer and display an error message there. On the other hand, an IOException while creating a temporary file could be handled lower down by retrying in another directory.
This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Assert keyword in java
assert vs. JUnit Assertions
I use JUnit for unit testing, but a lot of times its hard to get at certain things with JUnit. I have recently started looking at Java assert.
Is it a good idea to use assert and how would you recommend using it?
The most important thing to note is that using assertions and testing your code are two different (if perhaps related) tasks.
I think the assertions docs pretty much explain the kind of situations to use assertions.
Assertions are popular in languages without exception handling, for making checks to ensure the program is operating correctly, so as to make problems easier to diagnose.
However there can be some ambiguity as to what the most appropriate cause of action is if an assertion fires. If the program exits immediately, there may have been a wasted opportunity to handle the failure more gracefully (e.g. reporting the failure to the user and attempting to recover data). If the program does not exit immediately, it could be in an unknown state because of the error, which is also undesirable.
As a result it is considered better practice to throw exceptions in Java when a given condition fails, which allows a best-of-both-worlds solution to these problems. For errors that can occur during normal operation of the program, checked exceptions most appropriate. Calling code is obliged to handle these errors. For errors caused by failure internal program logic, throwing a RuntimeException would allow the program to handle the failure appropriately further up the call stack.
Asserts do have one benefit which is they can be employed in development, but can be 'compiled out' for a consumer or release build, where speed of execution is more of a priority than early detection and handling of errors. However apps that require that characteristic are not commonly built in Java (more likely C++), which is again why assert is rare in Java.
(Also, I believe that assets at runtime are not always enabled by default by some IDEs anyway, so it is easy to have an assertion fail and not know about it.)
Yes it can be useful to use assert to verify the correctness of your program run-time. I would typically use it to catch errors according to the fail-fast principle to actively detect bugs.
A typical use case would be that an operation succeeded. Consider the following sample:
int nChanges = database.update(..);
assert(nChanges == 1);
I wouldn't consider using it for parameter validation or any such operation which should be validated in regular code according to the contract, since it doesn't throw the appropriate exceptions (and run-time exceptions can be mean). Similarly I wouldn't use it in testing since JUnit already offers assert mechanisms which in contrast to regular assert statements cannot be disabled.
Checked exceptions need to be caught or declared to be thrown at compilation time but runtimeexceptions need not ...why we give important only to checked exception ...
In Java, the original inventors of the language wanted to distinguish between common types of exceptions, which may occur in a program. They came up with these three types:
Checked exceptions are used for errors, which may occur at run-time and are expected (sort of), for example, IOException. When doing file or network I/O, for example, an error may occur at any time (disk full, connection lost, etc.) The programmer has to be aware, that any operation called may fail at any time, and thus, the language enforces this kind of awareness by forcing the programmer to do something about the exception.
Unchecked exceptions are used for programming errors, such as NullPointerException, IllegalArgumentException, etc. These errors are usually the result of an oversight of the programmer, and constitute bugs in the program. They should not be handled by most parts of the code, as all guarantees about the state, the program is currently in and its consistency, are gone. One of the distiguishing features of a run-time exception is, that it is unexpected (you don't really expect there to be a bug in your program, right? -- except on the general level of "of course, I would not bet my life on this program being bug-free")
Errors, from which a recovery is hardly possible, such as OutOfMemoryError, AssertionError, etc. These exceptions are the really bad ones. These guys are usually never handled, and if they occur, will cause the program to crash.
Of course, in practice, many application will handle run-time exceptions (at least by logging them), and even Errors. And frameworks like Spring tend to blur the distinction further by making all exceptions unchecked (i.e., run-time exceptions) anyway. Interestingly, checked exceptions were considered for inclusion in C# and omitted, because they add a heavy burden on the programmer. Opinions vary on that topic, even today.
Taken from http://en.wikipedia.org/wiki/Exception_handling
Unchecked exception types should not
be handled except, with consideration,
at the outermost levels of scope.
These often represent scenarios that
do not allow for recovery:
RuntimeExceptions frequently reflect
programming defects,[19] and Errors
generally represent unrecoverable JVM
failures. The view is that, even in a
language that supports checked
exceptions, there are cases where the
use of checked exceptions is not
appropriate
Clearly mentions that it represents scenarios that do not allow for recovery
The division gives you flexibility: when thinking what kind of exceptions to throw, you should throw checked exceptions only when the application can reasonably recover from them (for example: "can't write file" is rarely a good reason to crash; rather, let's show a message to the user). Runtime exceptions are supposed to be fatal (programming errors), so it's better to let the program crash right away.
It was supposed to be a good idea. But it's just too complex in practice. The core problem is that the library and language designers are supposed to decide what kind of errors are fatal to an application (which doesn't even exist at that time!).
Did you know that while 1 / 0 results in ArithmeticException, 1.0 / 0 is a perfectly legal Infinity? Obvious - or not... And java.text.Format is supposed to convert an arbitrary object to String, but for some reason it throws an unchecked exception (IllegalArgumentException) if the object to be converted is somehow wrong type (e.g. null), so in practice you must remember to write a try-catch block whenever you use Format. Obviously someone thinks that converting nulls to strings is a fatal programming error. I would rather return an empty string. Your mileage may vary. The JDK is full of this kind of weird choices, and it clearly shows the problem of choosing between checked vs. unchecked.
This problem has made many people advocate unchecked exceptions only. I think it's just silly; most exceptions should be taken care of, because they signal something important. If I was a language designer, I would make all exceptions checked, but instead of a try-catch -block, one could use a plain annotation to say "I don't care about this exception" (which essentially would convert that checked exception into a runtime exception). This would give the benefits of checked exceptions (nothing goes unnoticed unless explicitly told so) AND the benefits of unchecked exceptions (no heavy try-catch blocks all around). It would be the application programmer's call to decide what's fatal and what's expected.
Of course, you can catch runtime exceptions if you want to. A plain catch(Exception ex) does it.
Look at the name of the exception "RunTime".
At compile time the compiler can see exactly what and where things can go wrong with most of your code.
However some objects/values can only be evaluated at run-time and unfortunately the compiler cannot foresee this.
e.g. casting an object to int, when it is in fact a string. You can only determine it at run-time. Thus a run-time exception will be thrown
Have a look at the common RuntimeExceptions:
ArithmeticException
ArrayIndexOutOfBoundsException
ClassCastException
EmptyStackException
IllegalArgumentException
IllegalMonitorStateException
NullPointerException
UnsupportedOperationException
Practically speaking: Most of those exceptions can occure everywhere and are most likely a programmers error, and as such are only needed to be handled in some kind of bug reporting handler. Other Exceptions show problems with the environment of the JVM, and need to be handled, because they cannot be guaranteed no to be thrown be the program alone.
if exception occurred at runtime then immediately JVM creates exception object and that object message is printed on console.
unchecked exceptions are occurred due to poor logic of our program.so program will be terminated abnormally.but JVM will not be halted.so JVM creates Excpetion object.
if we consider checked exceptions,for example,if we want to load some external file into our program , JVM is responsible for that.so,if any problems are occurred while that file is loading then JVM will be halted .so,then who creates exception object.this is the problem with checked excpetions .
to over come above problem we have to handle checked excptions at compiletime using throws keyword.
if you handle checked exception the following is done
-- JVM executes one by one statement , when it identifies throws keyword followed by checked exception then it creates checked exception object.so,when the exception is occurred then already created exception object is used to print the exception information on the console.
When you can handle the recovery of the state of Object , go for Checked Exception.
When you cannot handle the recovery go for UnCheckedException.
Mostly API developers go for Runtime Exception ,
they do not want to enforce handling exception by the user,
since they themselves do not know how to handle it
Runtime exceptions can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a program's clarity. Thus, the compiler does not require that you catch or specify runtime exceptions (although you can).