Not-an-exception exception in Java? - java

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

Related

Java: How to handle bad method arguments?

I'm writing a method with the following signature:
public void setCell(int index, String value);
The problem with this method is that the index parameter has a finite range decided at runtime, and the caller may accidentally use an out-of-bounds value for it. What should I do in this case?
I can think of three options:
Nothing -- let the whole thread crash and burn with an uncaught runtime exception
Immediately return if the index is out of bounds -- the caller will be unaware that the method failed but the program won't crash
Throw an exception / force the user to wrap calls in a try/catch block. This seems a bit overkill and tedious for the user of the method
In general, how do you decide which of these options to use?
Ideally, you'd want to throw an exception as early as possible (fail-fast) or let the exception happen naturally in which case it would hoist or bubble up to the calling method to indicate the cause of the exception rather than trapping the exception in a try/catch and letting the execution continue.
I'd also avoid option 2 which immediately returns if the index is out of bounds due to the fact that it's now impossible for the calling method to know if execution has successfully completed or not. in-fact this is a means of helping the program hide a bug rather than trying to signal it, which in a way relates to JB Nizet's comment.
It's better to keep the caller informed if the method being invoked successfully finished doing its logic or for some reason, it failed to do so.
throw an exception
You can even implement your own exceptions. Which case to use depends on your application and application design. Having uncaught or unhandled exceptions is probably the worst case most of the time.
if you have an user interface you can usually handle exceptions and inform the user, if you are implementing library functions you'll rather throw them and pass them to a higher level.

Java invariant exception

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

Java Propagating Exceptions

When would you want to propagate an exception to another Class/Method versus catching the Exception in the same Class/Method?
You catch the exception where you have to handle it.
As a rule of thumb, you should let your exceptions bubble up, but if you don't want your subroutine to crash due to a (possibly expected) error, than you handle the exception, which normally involves logging an error and/or displaying an error message to the user.
The good practice is "throw early and catch late". That allows you to better understand the cause of the exception.
This topic is fairly broad; fortunately there are good resources already in place:
Guidelines on Exception propagation (in Java)
http://www.javacodegeeks.com/2012/04/exception-handling-guidelines-best.html
Best practices for exception management in Java or C#
The great majority of exceptions occuring in real-life code are not recoverable in the sense there's any meaningful code that will retry the operation or try to do it differently. The only recovery happening is aborting the current unit of work in an orderly manner—logging the exception, releasing any resources and similar.
This means that, as a first rule, you'll always want to propagate the exception towards that well-defined exception barrier that demarcates your unit of work.
If your code demands anything different than this, it is probably going to be obvious enough, so you don't need to think about it in the general.

Java Error handling - is it better to throw Exceptions to centralized error handlers?

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.

why RunTimeExceptions need not to be caught at compilation time

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).

Categories

Resources