What's the difference between implicit exception and explicit exception?
If I declare catch block like: catch(Exception e). Is this implicitly declaring an exception, or explicitly?
Thanks in advance.
I don't believe there's any such term as "implicit exception" or "explicit exception". Are you thinking checked and unchecked exceptions perhaps?
I've just downloaded the language specification as a PDF, and the phrases "implicit exception" and "explicit exception" don't exist anywhere within it.
Could you say where you came across the terms?
I think implicitly instantiating an object is done without explicitly calling a constructor. I don't think you can do that in Java.
Example:
throw new Exception();
calls a constructor and then throws the newly created Exception object.
This only applies to the first part of your question:
The terms explicit and implicit exceptions do exist and relate to how a Java virtual machine handles exceptions. From the end-user (Java programmer) view, they are the same (besides the obvious performance benefit).
Explicit exceptions are ones explicitly checked for by the JVM. For example every array indexing operation you do, is explicitly checked for being in range by the JVM.
Implicit exceptions are ones that are thrown in the aftermath. For example NullPointerException and StackOverflowException are thrown in the handler routine for the segmentation fault. This is quite a performance boost as the JVM gets signaled by the OS instead of having to incur an overhead on every operation that might throw.
Neither. Catching is not declaring an exception. Declaring an exception happens on the method:
public void someMethod() throws Exception.
I'm not sure what you mean by implicit vs. explicit. You probably mean something like the difference between a runtime and checked exception, but you could also a mean a method which throws a Runtime exception, which is optional.
public void someMethod() throws NullPointerException
The throws in that case is purely optional, since it is a Runtime exception, nothing should happen differently.
Related
This question already has answers here:
In Java, when should I create a checked exception, and when should it be a runtime exception? [duplicate]
(14 answers)
Closed 4 years ago.
I am doing a code review and I have came across this method definition:
public void something() throws RuntimeException
Is there a rational reason to write 'throws RuntimeException' in Java?
RuntimeException is unchecked exception and therefore can be thrown from any place in the code. Saying "Hey, this method can throw RuntimeException" and knowing that any piece of code can do so may be redundant. The only reason I can think of, you would like to make it explicit is for documentation purposes, eg. "Throws RuntimeException when some specific thing happens", but then it probably belongs to javadoc, not to method signature.
Everything is context-dependent, of which you shared none; but on a general note in may be said that this very rarely makes sense. Methods declare unchecked exceptions for documentation purposes, but these are normally specific exceptions carrying some domain-specific meaning. Declaring to throw a completely generic unchecked exception is thus quite hard to justify, although I cannot say there is absolutely no situation where it may make sense.
Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.
This types of exceptions depend directly of code, for example, "ArrayIndexOutOfBoundsException".So, if you don't use arrays, arraylists, casting or something what could throw a RuntimeException, it wouldn't be neccesary to write that.
Any method can throw RuntimeException, like NullPointerException being most common. So if a method throws RuntimeException (or it's subclass), it's usually not put that in method signature.
So according to me, it just shows inmaturity of the programmer as it doesn't add any value. Though, it's not asked but even the method name i.e. something() is fishy. It doesn't convey any meaning to the reader.
This is my code:
public static void main(String[] args) throws Exception {
Scanner s = new Scanner(new File("story.txt"));
someFunction(s);
}
The story.txt is in the the project root, but without the throws Exception the code doesn't run.
Why?
You don't need throws Exception, but it won't hurt any if you leave it like that.
What you do need is a throws FileNotFoundException because the Scanner constructor you are using is declared to throw that exception, and you don't catch any exceptions.
You should throw a FileNotFoundException, because the Scanner constructor can throw one. Since it is a checked exception, you must either pass it further up the stack or handle it somehow.
I asked my professor, and he explained that Java makes you handle exceptions.
You must be ready for them if a function might throw them.
You can either use:
try {...
} catch { ...
}
to handle exceptions yourself, or you can use:
throws Exceptions
to "pass them to the next level" (handle them later).
Thanks for the help!
If a method or constructor either throws an exception which isn't derived from RuntimeException, or calls any method whose declaration indicates it must do so, then it must either catch that exception or declare that the exception may be thrown from it. This language feature is almost a good thing, but in its present form has been widely acknowledged as a mistake. Nonetheless, it is sufficiently firmly established as part of the Java language that it's not going anywhere.
Conceptually, it's good to make a distinction between exceptions which are likely to have special meaning to a method's immediate caller and those which would not. Unfortunately, the fact that an exception would have a special meaning to its immediate caller doesn't mean the immediate caller is going to be interested in it. The way Java implements checked exceptions, if Foo is declared as throwing a checked exception and Bar calls Foo but isn't prepared to handle that exception, it must either declare itself as throwing that exception (even though it's unlikely to have any special meaning to its caller), or else catch the exception it has no hope of handling (perhaps rethrowing as a type derived from RuntimeException). Catching and rethrowing as a type derived from RuntimeException is semantically the best approach, but ends up being the most verbose, especially if one wants to avoid making RuntimeException objects.
Note also that because there's no way a chained constructor call can be wrapped in a try block, any constructor which is chained through a constructor that is declared as throwing any exceptions is required to declare itself as throwing those same exceptions. Things are implemented that way for a reason, but it unfortunately makes it difficult for a class constructor to distinguish exceptions which got thrown as part of the base-class construction process and those which got thrown in the construction of the derived class.
Because, Scanner s = new Scanner(new File("story.txt")); throws checked FileNotFoundException. You should throws or catch checked exception for compilation.
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.
In the Below example if RuntimeException is replaced with some other exception then compiler throws the compilation error. But for Runtime Exception's it is not throwing anything. Why? Please explain.
class A {
public void process() {
System.out.print("A,");
}
}
class B extends A {
public void process() throws RuntimeException {
System.out.print("B,");
throw new RuntimeException();
}
public static void main(String[] args) {
A a = new B();
a.process();
}
}
RuntimeExceptions are what we call "unchecked exceptions".
This means, the compiler does not check whether they're caught in code.
The reason for this is, we have some exceptions that we often prefer to not have to handle or declare. For instance, NullPointerExceptions can potentially be thrown at so many places in the code, that it's more convenient if we only handle them, if we explicitly decide to.
See also:
In Java, when should I create a checked exception, and when should it be a runtime exception?
Unchecked Exceptions — The Controversy
Java unchecked/checked exception clarification
This has to do with checked vs unchecked exceptions. Here is another brief explanation
That's why it's called RuntimeException :)
Seriously, RuntimeException (all all exceptions inheriting from it) are called "unchecked exceptions" and the whole point is that they are NOT checked by the compiler.
This is required of a compiler, due to the following requirement in the Java Language Specification
11.2.5 Why Runtime Exceptions are Not Checked
The runtime exception classes
(RuntimeException and its subclasses)
are exempted from compile-time
checking because, in the judgment of
the designers of the Java programming
language, having to declare such
exceptions would not aid significantly
in establishing the correctness of
programs. Many of the operations and
constructs of the Java programming
language can result in runtime
exceptions. The information available
to a compiler, and the level of
analysis the compiler performs, are
usually not sufficient to establish
that such run-time exceptions cannot
occur, even though this may be obvious
to the programmer. Requiring such
exception classes to be declared would
simply be an irritation to
programmers.
For example, certain code might
implement a circular data structure
that, by construction, can never
involve null references; the
programmer can then be certain that a
NullPointerException cannot occur, but
it would be difficult for a compiler
to prove it. The theorem-proving
technology that is needed to establish
such global properties of data
structures is beyond the scope of this
specification.
Unlike checked exceptions, runtime exceptions (or unchecked exceptions) do not define a contract between the caller and the called method, for they usually indicate an erroneous condition, that is often resolved by the caller if it were to obey the contract.
If a compiler were to be given the task of enforcing such a contract, it would result in additional complexity (in the language itself and in the code that people write). Imagine, enforcing every method to check for null arguments and requiring programmers to throw such exceptions (and also declare such exceptions in the throws clause). The easier way out, is to specify a contract that states that a method will not operate on null arguments and that a caller should expect to catch NullPointerExceptions; if the caller wants to avoid this scenario, it must check the arguments before invoking the method.
The reason for that is the fact that checked exceptions declared for the overriding method must match with the signature of the method overridden. Otherwise the code won't compile due to the method signature mismatch. It is fine when you declare unchecked exceptions in overriding method, because these exceptions as the name suggest are not checked by the compiler.
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.