1
public class A extends Exception {....}
public class B extends A {....}
public class C extends RuntimeException {....}

Given the method signature A bar(B q) throws C, which of the following will not compile?

A.

A m() throws C {
    return bar(new B());
}     

B.

m() {
    return bar(new B());
}  

C. All of the above will compile.

The answer is C. There might be a typo with B, not sure. I'm not understanding this question, conceptually, what's it asking, etc. I get A is a superclass of B, and C is alone as a RuntimeException, so it's not checked at compile time?
And I get the inside of the method has to be a B time exception, which works in both answers. Could someone help explain why both of these compile?

sumitz1212
  • 63
  • 4
  • 10
  • 1
    Why *wouldn't* they compile? Can you explain what you think is contradictory here? – Thorn G Apr 26 '15 at 01:36
  • I don't really understand what is happening with the B. answer. It's not throwing a C, which the method signature does. And there's an A in front of m() in one answer and not the other. I don't understand the formatting of these questions/answer options to explain anything about their functionality. – sumitz1212 Apr 26 '15 at 01:41
  • 2
    B should fail because of no return type in the method signature. – Eranda Apr 26 '15 at 01:42
  • 2
    Sorry for offtopic useless comment, but I just wanted to say that A bar(B q) is just a barbecue (or at least it sounds like that). – petajamaja Apr 26 '15 at 01:43
  • 2
    @sumitz1212, yes, `bar()` throws `C`, but `C` is a runtime (a.k.a. "unchecked") exception. Methods *can* declare runtime exceptions that they may throw, but they are not required to do so. Not even if they call another method that does explicitly declare a runtime exception. – John Bollinger Apr 26 '15 at 01:51

1 Answers1

0

C is a kind of runtime exception. You don't need to declare a runtime exception, and they are ignored by the compiler.

Here's a good explanation to get started.

Declaring an exception doesn't mean there will necessarily be an exception. It just means that we should be prepared for the possiblility an exception is thrown.

Choice B will not compile, but not because of the exception. It will not compile because there is no return type. Choice A has declared a return of type A.

mmking
  • 1,564
  • 4
  • 26
  • 36