Error that is thrown - java

I'm passing through a java test and the following issue has come up:
Why is the following claim wrong?
An Error that might be thrown in a method must be declared as thrown
by that method, or be handled within that method.
I couldn't get an example of such an ill-formed program. I really have no idea.

an Error (as opposed to an Exception) is not a checked exception, and therefore doesn't have to be handled by the method or declared as thrown.
In fact, an Error usually shouldn't be caught, as mentioned in the Javadoc :
An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch.
It also says:
A method is not required to declare in its throws
clause any subclasses of Error that might be thrown
during the execution of the method but not caught, since these
errors are abnormal conditions that should never occur.

Related

Exception handling when overridden method does not throw any exception

Short form: How do you throw exceptions (or do nice, clean exception handling; or at least dirtily force execution to stop) when the overridden method doesn't throw exceptions?
Context: We have a license for a piece of proprietary software that can be automated using Java "macros". A user-defined macro must be of this form:
public class MyMacro extends SoftwareMacro {
public void execute() {
// user code goes here
}
}
i.e. a class that extents SoftwareMacro and that has a method called execute that overrides the base class' execute. The contents of this overriding execute are what gets... well... executed when the macro is "played".
But the overridden execute method apparently does not throw any exceptions.
execute() in com.mycompany.mypackage.MyMacro cannot implement execute() in
somesoftware.base.SoftwareMacro
overridden method does not throw java.lang.Exception
Maybe this is naïve, but while developing I usually like to have the appropriate exception type bubble up to the top and force execution to stop, so that I can see them and go on to debug. This is apparently not an option here.
Should I resort to throwing RuntimeException instead? (since RuntimeException does not need to be specified) That feels a bit sloppy, and a "violation in spirit" of the base class method contracy.
P.S. No, I can't change the source code of the overriden execute method.
Looks like the intent is that each SoftwareMacro do all its own error handling. Use a big try around your whole execute() method if need be, but don't let any exceptions escape. Do whatever cleanup you need to do inside your execute method, and possibly print an error message for the user, if they provide a way to do that.
You should examine all the APIs they provide -- perhaps there's an error reporting facility you're supposed to use.
It all depends on what the "Macro player" does if it encounters a runtime exception, and on what you want to happen.
If it doesn't handle it at all, but you don't care, throw a RuntimeException.
If it handles them properly, throw a RuntimeException.
If it doesn't handle them properly, and you don't want it to fail miserably, then catch the exceptions that might happen in your execute method, and handle them as you feel is the best: show an error dialog box, output an error message, log some error in the logs...
"Should" implies there's a right answer, which IMO there isn't do what meets your needs.
If the system can tolerate a runtime exception, and it meets your needs, why not?
Not that you have a choice, since you can't throw a checked exception.
(Checked exceptions seem like a failed experiment to me, although I understand the motivation.)
So long as the execute code doesn't absorb the exception, it will still throw it if one is encountered. If the kind of exceptions thrown are either RuntimeException or sub-classes of RuntimeException they don't need to be explicitly declared, mostly because the compiler doesn't enforce their declaration since (as the name implies) they only happen at runtime, and cannot necessarily be predicted at compile time.
If, however, the execute method, which you've said you can't modify, absorbs the exception, and doesn't indicate that exception via a log entry, return value, or some kind of RuntimeException I think you're out of luck.
I would agree with Ernest that it appears that the intent is that the execute method do all its own exception handling.
NOTE: Overridden method signatures don't need to match exactly when it comes to the exceptions they throw - just the name, return type, and list & type of variables.

rationale behind Java's exception hierarchy

I find Java's exception hierarchy confusing. Throwable is divided into Error and Exception, and RuntimeException inherits from Exception.
Error is an unchecked exception. Why doesn't Error inherit from RuntimeException then?
Exception is a checked exception. RuntimeException is an unchecked exception, yet it inherits from Exception. Doesn't this violate the Liskov-Substitution-Principle?
Wouldn't it make more sense if Throwable were divided into Exception (checked) and RuntimeException (unchecked), and Error would inherit from RuntimeExeption?
I find Java's exception hierarchy confusing. Throwable is divided into Error and Exception, and RuntimeException inherits from Exception.
A Throwable is anything that can be used to unwind the call stack. This should include some VM level fault (flagged by an Error) and something application specific (flagged by an Exception)
Error is an unchecked exception. Why doesn't Error inherit from RuntimeException then?
Simply because Errors are not Exceptions. There wouldn't be any point in actually "catching" an Error. For eg. What would you do after catching an OutOfMemoryError. Errors are meant to flag something seriously happened at the VM level which is not necessarily handle-able by the programmer
Exception is a checked exception. RuntimeException is an unchecked exception, yet it inherits from Exception. Doesn't this violate the Liskov-Substitution-Principle?
Not really. What the implementors were trying to say was that Exceptions MUST always be checked. Your code will be cleaner if all your methods declare what sort of application/library Exceptions they throw. RuntimeExceptions should only be thrown in case of more general / dynamic situations such as a NullPointerException where the developer might not have coded for the case but is a serious bug which is not exactly something mentioned in the application spec.
The design of exception handling in the two most popular object-oriented frameworks (Java and .NET) is predicated upon the notion that the question of whether to handle a particular exception should depend primarily upon its type, and that the types of exceptions one will want to catch are going to have a hierarchical class relationship. I think Java and .NET do things that way because C++ did it that way, and C++ did it that way because of a desire to avoid hard-wiring any non-primitive types hard-coded into the language. In the absence of a hard-coded type to which all exceptions may be cast, it's impossible for a catch statement to know anything about any exception type for which it is not explicitly prepared. If it will only make sense to catch exceptions one can decode, a catch statement will be able to sensibly act upon those types, and only those types, which derive from the one in the statement.
In retrospect, it probably would have been better to have the decisions of what exceptions should be acted upon and/or resolved by particular catch statements be determined by some means other than the class hierarchy. Among other things, a single attempt to invoke a method may fail because of multiple problems; if that happens, every catch which is associated with any of those problems should trigger, but only when all of the problems have been resolved should normal execution resume. Unfortunately, neither Java nor .NET has any mechanism to achieve such behavior.
With regard to the top-level layout of the hierarchy, I think there was an assumption that every kind of exception that might be thrown by a method would either always be expected by the immediate calling code or never expected by any calling code. Exceptions of the latter type were classified under Error or RuntimeException, while those of the former type were placed elsewhere. In practice, the question of whether an exception is expected by a method's caller should be independent of its place in the hierarchy or even the exception type. The fact that a method is declared as throws FooException does not mean that calling code is always going to expect that the exception could occur. It's very common for code to call a method which is declared as throwing an exception but believe that the circumstances surrounding the call are such that in practice that the particular call won't ever throw.. If the exception does occur, it should behave like an unexpected exception, even if an outer execution context is expecting to catch an exception of that type. Unfortunately, the exception handling mechanisms are what they are, and I don't expect any major overhaul.
I think that even better hierarchy is
Throwable
Exception
CheckedException
RuntimeException
Error
This hierarchy separates Exceptions and Errors (as #Paarth said) and makes it possible to catch all checked exceptions only (without runtime exceptions). But it seems that James Gosling thought different...
Error is not a subclass of Exception because it is not meant to catch (Once an error is occurred usually the program is no longer expected to function). So error should have more higher place in hierarchy as I believe.
It should not violate Liskov substitution because RuntimeException can be catched if you want, but only it's not enforced.

do checked exceptions happen at run-time?

I am confused with the naming of runtime exception of java.
Those checked exceptions, like SQLexception, also happen during the execution of a program.
Why only those unchecked ones called runtime exception?
It is probably I have misunderstanding of "runtime".
Thank you for any advices.
I can understand your confusion. All exceptions occur at runtime!
The only reason I can come up with for naming the class that way, is that it clarifies that it is an exception that doesn't have to be dealt with at compile time.
As opposed to all other so called "checked" exceptions, RuntimeExceptions doesn't require the programmer to declare the exception to be thrown using a throws clause.
RuntimeException is a subclass of java.lang.Exception. RunTimeExceptions are almost always the result of a programming error or/and invariants not being met (Nulls being passed when they shouldn't), so you do not have to catch them like java.lang.Exception (which is Checked Exceptions). You don't catch them because there's little the Run Time system could do to recover.
I think the phrase runtime just means they happen when the program is running (obviously!!) and crucially the compiler doesn't force checks to be built into the code as with Checked Exceptions. I think it's an example of where it's difficult to name a class appropriately e.g. I guess they could have Exceptions unchecked by default and called it Exception. Then subclassed it to provide CheckedException - everyone calls java.lang.Exception a Checked Exception, but it's not clear from the Class Name. But they didn't and we have:
> java.lang.Exception is referred to as "Checked Exception"
> java.lang.RuntimeException is referred to as "Unchecked Exception"
Yes, the naming is a bit confusing but it reflects the nature of an Exception being handled, not its time of occurrence.
All the exceptions occur at runtime. However, you are forced to handle the behavior of your program yourself for a specific type of exceptions i.e. CheckedExceptions. The reason is that these types of exceptions are more likely to occur. Example FileNotFoundException.
On the other hand, UnchekedExceptions[aka RuntimeExcetions] are less likely to occur and the programmer is not forced to handle those while writing the program. Ex: ArithmeticException.

What is the difference between throws Throwable and throws Exception

Any difference about those two?
Exceptions are for errors in the program logic. Error are used by the JVM to signal that something is wrong with the environment such as an OutOfMemoryError or IncompatibleClassChangeError. ThreadDeath is used to kill Threads. Throwable is a super class over all of these.
In normal program logic, you should never throw nor catch Throwables or Errors. The main reason I can think of for catching a Errors is this: You are using your own class loading system and want to isolate broken plugins.
The JavaDoc for ThreadDeath for example says:
An application should catch instances of this class only if it must clean up after being terminated asynchronously. If ThreadDeath is caught by a method, it is important that it be rethrown so that the thread actually dies.
The Throwable class is extended both by the Exception class and the Error class, so by using throws Throwable you are actually saying that your method may not only throw an Exception but also an Error. The difference between the two according to the documentation is that Exceptions are
conditions that a reasonable application might want to catch
while errors indicate
serious problems that a reasonable application should not try to catch
See here for more details.
This is the hierarchy
java.lang.Object
java.lang.Throwable
java.lang.Exception
Throwable Java Doc
The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement. Similarly, only this class or one of its subclasses can be the argument type in a catch clause.
Instances of two subclasses, Error and Exception, are conventionally used to indicate that exceptional situations have occurred. Typically, these instances are freshly created in the context of the exceptional situation so as to include relevant information (such as stack trace data).
Exception Java Doc
The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.
Please read the doc, it explains.
A Throwable could be a Error or Exception.
From 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 class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.
If a Throwable could only be an Error or an Exception, there would be no difference between throws Throwable and throws Exception for a method, as Error can be always thrown, even if it was not declared (like RuntimeException, too).
But a method declared with throws Throwable can also use throw new Throwable("example");, or something like this:
class CannonBall extends Throwable {}
throw new CannonBall();
There normally is no reason to do something like this, so in practice throws Throwable and throws Exception are equivalent.

Error class in Java

I am trying to understand the Error class in Java.
I have a good understanding of the Exception class, but can't find examples of code for the Error class. I've tried searching the web and also the java.sun website, but I'm not finding anything useful to help me understand this better.
How do I use the Error class in programs and where do we have to use that?
You don't use Error in your code.
An Error is a specific kind of Throwable, just as Exception is.
Throwable is the base class that defines everything that can be thrown.
Exception is the common case. It is about problems that occur during the execution of your program.
RuntimeException is a special case: it's unchecked (i.e. it need not be declared by a method and the compiler doesn't force you to catch it).
Error is the "rare" case: it signifies problems that are outside the control of the usual application: JVM errors, out of memory, problems verifying bytecode: these are things that you should not handle because if they occur things are already so bad that your code is unlikely to be able to handle it sanely.
You should not attempt to correct the situation that resulted in an Error. You might want to catch it in order to log it and then rethrow it (see the JavaDoc of ThreadDeath for an example on why you need to rethrow it (thanks to #krock for the heads-up)).
There is no other reason to throw any Error (i.e. don't create an Error on your own and throw it, if you think you want to do that, use an Exception or a RuntimeException instead).
If you take a look at the Javadoc here there is a good explanation:
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.
Concerning the usage you also have this:
A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur.
Error
Error a subclass of "Throwable" class is thrown by java runtime system and indicate some unrecoverable conditions during the execution of the programs
Once thrown difficult to recover from it and the application get to halt.
Eg..,java.lang.StackOverflowError and java.lang.OutofMemoryError
// An example code which throws StackOverflowError
public class ErrorDemo
{
public void method1()
{
this.method2();
}
public void method2()
{
this.method1();
}
public static void main(String sri[])
{
ErrorDemo k= new ErrorDemo();
k.method1();
}
}
In this code from main method we are calling method1 and from method1 a call was made to method2 and again from method2 we are calling method1 means we created a continous loop which doesn't goes to end and finally a critical error StackOverflowError is being thrown.

Categories

Resources