I have a kludgey use of Java RuntimeError in which I fully handle the error. Only problem is it gives me annoying trace telling me where the runtime error that I derived and threw occurred. How to suppress this trace?
For reference, the issue is I subclassed a non-throwing class and needed my subclass to throw. It was either "rewrite my program to read like a C program" or "use runtime error to bypass throw specification requirement." Obviously I'm finding the throw spec requirement very counterproductive right now - other workarounds that don't involve maintaining a bunch of "workIsDone" variables would be appreciated.
Without code it's awfully hard to know what you're talking about, but in general, stack traces come from a handler catching an exceptions and calling printStackTrace() on it. The stack trace doesn't appear unless something asks for it. Now, if an exception makes it all the way to the top of (for example) the AWT event thread stack, then the default handler will print it out this way.
As a rule, you want to handle exceptions. It can be a fine strategy to use runtime exceptions to get around the fact that some superclass method doesn't declare any exceptions, but then you take responsibility for always catching those exceptions. If you can't -- i.e., if some other code is going to catch them instead -- then this is a bad strategy and you can't use it.
Related
In what use case would a custom Error class be required?
I know there are many specialised subclasses of Error in Java API (e.g. LinkageError, ServiceConfigurationError, ThreadDeath, VirtualMachineError) but I think these are only required by the Java runtime and mostly are not required in the application code of a Java developer.
I am well aware about creating custom Exception classes and their usage scenarios, but I'm not sure about Error.
As the documentation describes:
An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch.
Exceptions, on the other hand, are designed to be caught. Unchecked RuntimeExceptions should be caught judiciously (because the code that raised it is indicating something unexpected happened) but the JVM itself is in no danger; if the caller believes it can recover from the RuntimeException, it's safe to do so.
Therefore if there is something in your program that no "reasonable application" would ever want to handle, an Error is appropriate. This is very, very rare however.
Look at some of the existing subclasses, like LinkageError and VirtualMachineError and it's subclasses InternalError, OutOfMemoryError, StackOverflowError, and UnknownError - these are raised when the JVM has failed and there's nothing it can do to recover, not even let the user try to handle it.
If you have an additional case where your code could fail catastrophically and you want to similarly force the application to terminate, use an Error (probably an AssertionError). The vast majority of the time, however, a RuntimeException of some sort is sufficient, as it allows a user to at least try to correct the problem while the program is running.
I have been reading the JLS and I encountered the section 11.1.3. Asynchronous Exceptions from which I quote:
Most exceptions occur synchronously as a result of an action by the
thread in which they occur, and at a point in the program that is
specified to possibly result in such an exception. An asynchronous
exception is, by contrast, an exception that can potentially occur at
any point in the execution of a program.
And
Asynchronous exceptions occur only as a result of:
[...]
An internal error or resource limitation in the Java virtual machine that prevents it from implementing the semantics of the
Java programming language. In this case, the asynchronous exception
that is thrown is an instance of a subclass of VirtualMachineError.
Is it possible to catch such exceptions for logging purposes or notification (because I believe such thing is unrecoverable)? How can I achieve such thing?
You can catch such exceptions just like any other exception. The only problem is that they may occur at any place in your program, so catching them reliably is hard. You would basically have to wrap the run method of all threads and the main method in a try..catch block, but you can't do that for threads you don't control (like the Swing EDT, or threads for timers etc.).
Also catching any subclass of Error is usually not recommended, because the JVM may be in an unstable state, which might lead to a further failure (for example in the case of OutOfMemoryError, you might not even have enough memory to to the exception handling). However, logging would be a valid reason for catching Errors in my eyes.
My suggested solution would be to use an uncaught exception handler for this by setting it as the default exception handler. In this handler you will get all exceptions and errors, if they are not caught anywhere in the code, and you can try to log them.
There is no point of catching these exceptions (Subclasses of VirtualMachineError) as you have no indecattion in which state the pogram is at the point, the Doc saies about Virtual Machine Errors:
A Java virtual machine implementation throws an object that is an
instance of a subclass of the class VirtualMethodError when an
internal error or resource limitation prevents it from implementing
the semantics described in this chapter. This specification cannot
predict where internal errors or resource limitations may be
encountered and does not mandate precisely when they can be reported.
so assuming you get in an OutOfMemoryError or an UnknownError there isnt much you can do about it, and once your vritualmashine doesnt work properly you cant provide the user anyhelp as your program isnt working properly as well, besides you have no idea at what time, point, and reason it happends since its not a code error that was caused from your program.
Since there is no need to try/catch or specify un-checked exceptions, how are they are reported to the user?
how are they are reported to the user?
What is the best practice to handle
un-checked exceptions?
In our application, we barely use any exception at all: neither checked nor unchecked (we consider checked exceptions to be a Java idiosynchrasy unrelated to the problem domain we're dealing with, so we wrap most checked exceptions inside cleaner APIs, using state testing methods).
The way we deal with it is simple: it's a desktop application, if we catch an uncaught exception, we offer the user the possibility to send us a report. All the user has to do is click on "Report" and we get the full stack traces and other infos sent to one of our servers.
You can set up an application-wide uncaught exception handler like this:
Thread.setDefaultUncaughtExceptionHandler( new Thread.UncaughtExceptionHandler() {
public void uncaughtException( final Thread t, final Throwable e ) {
...
// Here we offer our user the possibility to 'report' the exception, YMMV
}
}
Typically there are zero exception happening in our software: we don't use checked exception for flow control (unless when we're using brain-dead APIs from the nineties, where this was common practice).
Some frameworks, like Spring, also have a pretty strong preference towards the "no checked exceptions" mentality.
So exceptions for us are really exceptionnal, hence the popup warning the user that the app crashed and offering them the possibility to send us the report.
If you are writing a container or a framework or a UI framework, then the best place to handle them is centrally, propagate them all the way to central handler and report the error to user in a usable way,
If using a UI, provide a way for user to report that exception.
Details:
We generally use a practice when using UI is that have a central exception handler.
In case of a web UI, we have on handler that shows the user that something has gone wrong in the system, The error page also has a form with hidden fields that has stack trace along with a description (optional) field asking the user to describe what she/he was doing when error occured. The for submits the error information, with stacktrace to the system (which can be a mail or simply stored in db)
In a desktop UI, could be the same, only thing that will be different is where you put your exception handling code.
Error reporting example
Error reporting example http://www.flickr.com/photos/aniketn/4785197367/
You actually can catch unchecked exceptions. It's just that they're usually things you can't solve when you do catch them - for example, NullPointerException. There's generally not a way to smoothly and gracefully resume whatever you were doing when the NullPointerException occurred.
If you don't handle them, they will propagate all the way up through your program and it will abort, dumping a stack trace of the exception.
The best practice is to deal with the ones where you can provide some better handling than the default. For example, if you call an external library function, you could wrap it in a try/catch block and if the library throws a NullPointerException you could give the user a friendly error message (a GUI "library X failed to do Y - did you specify a valid Z?") instead of a stack trace on the command line. But in the general case, the reason they're unchecked is because even if you knew about them, there'd be nothing for it but to throw up your hands.
When bubbling out of the main(...) method, the JVM prints the stack trace to System.out and exits that thread. For single-thread programs, that would also exit the program.
In general, every thread you run should have a wrapper catching Throwable so you can at least log it to your files.
This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
When to choose checked and unchecked exceptions
Why does Java as a language have both checked and unchecked exceptions. What purpose do they serve?
Note: I'm not asking when I should use them, or how to code them, but what they add to the language.
The theory for checked exceptions is simple.
When designing an interface, think of exceptional cases that can occur, and will occur, with the normal state of a method call. Declare these exceptions in your interface, as the programmer will have to handle them directly.
For example, a bank account withdraw method may declare an OverdraftException, which is an expected exception - a withdrawal may fail due to overdraft, but this type of failure may be handled differently by the client code (one may decide to completely deny the withdrawal, another may decide to apply a huge penalty and allow for a negative balance to be recorded, another may decide that their client is allowed to draw from a different account).
However, runtime exceptions were supposed to be programming errors that weren't supposed to be handled directly - such as NullPointerExceptions, which only occur if methods take invalid arguments or don't check for such cases directly.
This is a good theory. However, Java messed up with its implementation of Exceptions, and this threw the book of this theory out the window.
There are two cases that I will illustrate where Java messed up with its implementation of Exceptions. These are IOException and SQLException.
An IOException occurs anytime, anywhere a stream in the IO libraries of Java messes up. This is a checked exception, however. But, generally you cannot do anything but log that an error occur - if you're simply writing to the console, what can you reasonably be expected to do if you suddenly get an IOException when you're writing to it?
But there's more.
IOException also hides stuff like file exceptions and network exceptions. They may be subclasses of IOException floating around for that, but it is still a checked exception. If your writing to an external file fails, you can't really do much about it - if your network connection is severed, ditto.
SQLException is the same way. Exception names should show what happened when they are called. SQLException does not. SQLException is thrown any single time any possible number of errors are encountered when dealing with a database - MOST OF WHICH THAT HAVE NOTHING TO DO WITH SQL.
Therefore, programmers typically get annoyed with handling exceptions, and let Eclipse (or whatever IDE they're using) generate blocks like this:
try {
thisMethodThrowsACheckedExceptionButIDontCare();
}
catch(Exception e) {
e.printStackTrace();
}
However, with RuntimeExceptions, these intentionally bubble up and eventually get handled by the JVM or container level. This is a good thing - it forces errors to show up and then you must fix the code directly instead of ignoring the exception - you may still end up just printing the stack trace (hopefully logging it instead of printing to the console directly), but then there will be an exception handler that you were forced to write because of a real problem - not because a method said that it might possibly throw an Exception, but that it did.
Spring uses a DataAccessException to wrap SQLExceptions so that you don't have to handle them as a checked exception. It makes code much cleaner as a result - if you expect a DataAccessException, you can handle it - but most of the time you let it propagate and be logged as an error, because your SQL should be debugged by the time you release your application, meaning the DataAccessException is probably a hardware issue that you could not resolve - DataAccessException is a much more meaningful name than SQLException, because it shows that access to data failed - not that your SQL query was nessecarily at fault.
They add a differentiation between errors that the designer of a library feels must be caught, and ones that they feel the programmer shouldn't handle.
For example it might be reasonable for a program to handle bad input from a user, but if something goes wrong with the underlying OS and threads starts to die without reason, it isn't something that the program should be expected to handle.
Personally, I think checked exceptions were a mistake in Java.
That aside, designating both checked and unchecked exceptions allows a library to differentiate between recoverable and unrecoverable errors. By making all recoverable errors throw checked exceptions, a library/language can force a developer to handle the edge cases they might otherwise paper over.
The big problem with this:
try{
myCode();
}catch(Exception e){ //Do nothing }
Additionally, in most cases it really is best to just throw up your hands and pass an exception up when one occurs. By forcing checked exceptions to be declared, a method that really doesn't care if an error occurs ends up having dependencies (in terms of compatibility, but also code-smell and others) it really shouldn't.
I think Sun initially thought it would be a good idea because the programmer is forced to handle the exception. However, many years later, pretty much everyone agrees they are a bad, unneccessary addition.
One of the main issues (apart from cluttering code) is that they leak abstractions form lower layers to higher layers (such as rmi remote exceptions)
Checked and unchecked exceptions invokes a bit of a religious argument - Java fell one side of the fence, C# the other.
In Java checked exceptions should be used when the calling code can recover from the error as where unchecked exceptions are used when there's a critical error (with perhaps the exception - no pun intended - of NullPointerException) that the calling code is unlikely to be able to recover from.
Personally I like to have both available to me generally favouring checked exceptions because they allow me to force the calling code to deal with an error situation that a developer might otherwise have ignored (although the infamous empty catch block side-steps this).
I don't think there's anything at all conceptually wrong with checked exceptions... but they do tend to suck mightilly in practice, because (especially early) library developers over-use them.
Also the "catch or declare" requirement does NOT fit well with interfaces.
My basics thoughts are: "Stuff that goes wrong" comes in two basic flavours: recoverable, and unrecoverable... Ergo: Business Exceptions and System Errors.
For instance: What do you (the library developer) expect me (the application programmer) to do about recovering from a failure in a call to SomeStream.close()? Yes, I definately need to be made aware that something has gone horribly wrong, but really my only option is to terminate the program/request/process/thread which tripped over it. I cannot be reasonably expected to even attempt to recover from the situation... Ergo: It's an uncoverable error, and therefore I shouldn't be forced to write a lot of highly repitious boilerplate catch-blocks which don't handle the problem at every level of the (potentially very deep) callstack. Therefore I believe it would be better if "catch all" checked exceptions such as IOException had never been invented... CloseException extends UncheckedIOException would be more appropriate, IMHO.
Also, if I had a time machine I'd go back in time and plead with the Java gods for:
interface Throwable
abstract class Exception
abstract class CheckedException
abstract class UncheckedException
class Error
Also: I'd love to see a #FaultBarrier class-annotation, which makes the compiler enforce: All exceptions (especially unchecked ones) must be caught or explicitly thrown. The most horribilest hunk of system I've ever worked on was riddled with throwings of raw RuntimeException; It's enough to make you weep.
Cheers. Keith.
when an exception occurs that a method is unable to handle - does the program terminate and show the error number ? where does the error number and information about the error come from ? should the programmer while coding have an idea what kind of exception might occur. if so why does'nt he ensure that exception does not occur .
If you are using Java APIs, the exceptions that each method throws are documented.
When the program terminate, it shows an stacktrace of the methods calls that caused that specific problem.
Check the lesson on Exceptions from The Java Tutorial. You can learn much more reading there than reading my answer here :)
There are 2 main types of exceptions in Java:
- checked
- unchecked
unchecked exceptions are further broken into RuntimeException and Error.
RuntimeExceptions are programmer errors (ArrayIndexOutOfBoundsException) and Errors are things that are problems in the VM (OutOfMemoryError).
You should not catch RuntimeExceptions - you should fix your code so it does not throw the exception.
You should not catch Errors since the VM is likely in a state that you cannot do anything to recover from them.
If your main does not catch an unchecked exception it will crash.
Java Exceptions bubble-up to the point where someone catches them, or to the point the program exits.
In the real-world, when many frameworks are used, exceptions never bubble-up to the top. They are caught and reported (printed on console). Catching exceptions is done by the try { } catch(..) { } block.
There are two types of exceptions - checked and unchecked. The checked exceptions must be declared in the method signature (unlike the unchecked)
should the programmer while coding
have an idea what kind of exception
might occur
Yes, but no one's perfect.
why does'nt he ensure that exception
does not occur
In exceptional circumstance, you WANT an exception. You do not want to ignore the exception.
For example, suppose that your program creates a file to save user settings. If for some reason
the file creation fails (which your program has no control over, it's the Operating System's job), you do not want to go on like nothing happened. You want there to be an exception, so that whoever or whatever function called that function knows about this problem, and can do something, e.g. inform the user.