For example:
FileWriter saveFile = new FileWriter("text.txt");
This code shows the error:
Unhandled exception type IOException
What does this mean?
Java has checked exception mechanism.
It means every exception (which is not RuntimeException) that is thrown by a method must be handled by the method internally or be declared the is throwing it (in its declaration).
In your example, the constructor of FileWriter is throwing IOException, so you should either handle it internally in the method by try-catch blocks, or make your method's signature declared it might throw it.
There are exceptions which Java compiler forces to be handled by developer & need properly propagated to caller.
These exceptions fall under the category of checked exception(compile time exceptions).
Either with try{...}catch{...} or with throws keyword these type of exceptions must be handled by developer.
The class Exception and any subclasses that are not also subclasses of RuntimeException are checked exceptions. Visit java doc here
Related
below is a multiple choice question, I think (A) and (D) both right,but standard answer is (D)
Which of the following statements is true?
(A) An exception can be thrown by throw keyword explicitly.
(B) An RuntimeException must be caught explicitly.
(C) An uncaught NullPointerException will cause a compilation error.
(D) An overriding method can throw a different exception from its overriden method.
The statement of (A) is wrong ? I need help.
Thanks in advance.
The throw keyword allows an exception inside of a function and the throws keyword is used in the throw statement of the method signature to state what exceptions might thrown by the function.
EX:
public static void brokenFunc() throws Exception {
throw new Exception();
}
Now an overriden method cannot throw an exception that is broader than the exception of the super method. The only time this is an exception (did you see what I did there?) is when it's a runtime exception because they are unchecked exception. This would mean that option A is correct.
Making edit to address how the answer could be D.
The interview made a mistake and meant throws not throw
D refers to unchecked exceptions
D refers to overloaded method not overriding method
D means extending exceptions as different exceptions
If you google search answer A, you'll find a large amount of sources that states an exception can be thrown by throw keyword explicitly. There is not way to say that D is the standard question. No version of Java supports different exceptions from overridden methods because all checked exceptions will extend the exception from the super method. Extending exceptions has a is a relationship to the super exception so it is not "different". Runtime exceptions are not referred to as exceptions only because that does not make sense. A runtime exception is an exception but an exception is not a runtime exception in java so that should not be the case used in this question. This makes it seem like the interview was wrong to some degree and did not phrase the question correctly. I personally would not want to work there.
Why throws, on a method, is part of its signature? It seems strange to include it. Here is an example where it is in the way:
#Overide
public void foo() {
throw new UnsupportedOperationException();
}
If anyone were to see this method from the outside, they might try to use it without knowing that it is not supported. They would only learn it on trying to run the code.
However, if they could do something like this they would know by looking at the method that it is not supported and if UnsupportedOperationException was not extending RuntimeException, they would get a compilation error. EDIT1: But this is not possible because throws is part of the signature so override will not work.
#Overide
public void foo() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
This question concerns Java's design, so I know that it might be hard to answer without one of the people that work on it drops by and answers it, but I was hoping that maybe this question has been asked to them before or that there might be an obvious reason to have it this way to explain why.
The throws part does not indicate that the method is required to throw the mentioned exception(s), not even at particular occasions. It only tells that the function is allowed to do so.
Including throws UnsupportedOperationException will consequently not mean that the method is unsupported. Besides the UnsupportedOperationException is a RuntimeException so a method may throw that anyway.
Now for the reason one would require it in the signature of the method, it boils down to the ability to have checked exceptions at all. For the compiler to be able to decide if a method can only throw the specified exceptions it must be able to decide that the methods that it calls can't throw uncaught exceptions.
This means for example that overriding a method means that you can't add exceptions that might be thrown, otherwise you would break the possibility to verify that a method that calls that method can't throw anything else than it has specified. The other way around would be possible (but I'm not sure if Java supports that), overriding a method that may throw with one that may not throw.
So for example:
class B {
int fubar(int) throws ExceptionA {
}
int frob(int) throws ExceptionA {
return fubar(int);
}
}
class D extends B {
int fubar(int) throws ExceptionB {
}
}
Now frob is specified to possibly throw only ExceptionA, but in calling this.fubar it would open the possibility that something else is thrown, but fubar is defined to possibly only throw ExceptionA. That's why the D.fubar is an invalid override since that would open up the possibility that this.fubar actually throws ExceptionB and the compiler wouldn't be able to guarantee that frob doesn't throw ExceptionB.
Java has two different types of exceptions: checked Exceptions and
unchecked Exceptions.
Unchecked exceptions are subclasses of RuntimeException and you don't have to add a throws declaration. All other exceptions have to be handled in the method body, either with a try/catch statement or with a throws declaration.
Example for unchecked exceptions: IllegalArgumentException that is used sometimes to notify, that a method has been called with illegal arguments. No throws needed.
Example for checked exceptions: IOException that some methods from the java.io package might throw. Either use a try/catch or add throws IOException to the method declaration and delegate exception handling to the method caller.
One thing which no one has mentioned is a very important answer to your question:
Why throws, on a method, is part of its signature?
that throws, is NOT part of the method signature.
JLS 8.4.2. Method Signature makes it quite clear, that:
Two methods or constructors, M and N, have the same signature if they have the same name, the same type parameters (if any) (ยง8.4.4), and, after adapting the formal parameter types of N to the type parameters of M, the same formal parameter types.
If anyone were to see this method from the outside, they might try to use it without knowing that it is not supported.
That's exactly the main reason, why throws is designed in a way to be checked at compile-time for all Checked Exceptions - clients of the method will be aware what this method may possibly throw.
Checked Exceptions are enforced to be either handled or specified to be thrown (but this specification is NOT part of the method signature).
Unchecked Exceptions do not have to be either handled or specified to be thrown, and Oracle's tutorial are good at explaining - why:
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 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.
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.
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.