Java Programming - Exceptions - Discussion

Discussion Forum : Exceptions - Pointing out the correct statements (Q.No. 3)
public class ExceptionTest 
    class TestException extends Exception {} 
    public void runTest() throws TestException {} 
    public void test() /* Point X */ 
At Point X on line 5, which code is necessary to make the code compile?
No code is necessary.
throws Exception
catch ( Exception e )
throws RuntimeException
Answer: Option

Option B is correct. This works because it DOES throw an exception if an error occurs.

Option A is wrong. If you compile the code as given the compiler will complain:

"unreported exception must be caught or declared to be thrown" The class extends Exception so we are forced to test for exceptions.

Option C is wrong. The catch statement belongs in a method body not a method specification.

Option D is wrong. TestException is a subclass of Exception therefore the test method, in this example, must throw TestException or some other class further up the Exception tree. Throwing RuntimeException is just not on as this belongs in the java.lang.RuntimeException branch (it is not a superclass of TestException). The compiler complains with the same error as in A above.

4 comments Page 1 of 1.

Arfat said:   7 years ago
Public void test() method belongs to ExceptionTest class which does not implement any interface so it's a regular method that does not throw any exception.

Anusha said:   8 years ago
It compiled Successfully if we write the code either throws Exception or throws TestException in place of /*Point X/.

Because the runTest() throws an TestException it is subclass of Exception so when we call runTest() in any method that method /*(In which method we calling runTest())*/ also caught either TestException or Exception.

For compilation the compiler doesn't check for main method Run time only JVM checks for main method. So it is successfully compiled but not executed.

Akash said:   9 years ago
There is no main method so it is not compilable.

Sonam said:   1 decade ago
Whenever we call any method that is throwing any exception we have two options:
either surround the calling method with try-catch block or throws exception.

Post your comments here:

Your comments will be displayed after verification.