In Java, what happens if code is written that could throw a checked exception in a method that has no throws clause for that exception, and there is no catch block defined in the method to handle that particular exception class?
A. If an accessible catch block exists for one of the exception’s ancestor classes, then the program compiles and runs.
B. If there is no catch block that can handle the exception, the code will not compile.
C. If the exception is thrown, and there is no catch block that can handle the exception, the program halts.
D. If the exception is thrown, and there is no catch block that can handle the exception, the program continues, but its results are unpredictable
E. Both A and B, taken together, fully describe what occurs.
thanks a lot
What's the answer to this problem and can you explain?
Yes the answer is E.
Reply:The answer is E; Both A AND B. Somewhere, the exception must be caught, or the code will not compile. Take for example ( in semi-pseudo code):
class ParentClass {
...
parentMethod {
childClass.childMethod();
}
...
}
class ChildClass {
childMethod {
FileInputStream myFile =
new FileInputStream("/path/to/my/file");
}
}
It is okay (although bad programming) that childMethod() does not wrap the call to 'new' for the FileInputStream in a try/catch block. However, the app will not compile because parentMethod() does not wrap the call to childMethod in a try/catch block.
To make this program compile, we would need to do this:
class ParentClass {
...
parentMethod {
try {
childClass.childMethod();
} catch (Exception ex) {
// handle it
}
}
...
}
class ChildClass {
childMethod {
FileInputStream myFile =
new FileInputStream("/path/to/my/file");
}
}
In this instance, because parentMethod() wraps childMethod() in a try catch block, and we are catching an Exception through which FileNotFoundException is accessible.
Reply:The answer is A. Let's say we have Exception class and IOException class which extends the Exception class. Writing catch clause for Exception will also catch IOException, because IOException IS-A Exception. It's just a common sense.
To the posters below me:
The answer is not E. You do not have to declare catch block for the Exception if you already declared catch block for the Exception's superclass.
catch (Throwable e) {} - There, I will catch EVERY SINGLE exception, checked/unchecked, and I don't have to declare any other catch clauses.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment