views:

72

answers:

2

I have class A in which I have a method openfileConnec(). It was written like the below:

public void openfileConnec() throws Exception {
    //code for opening a file
}

Now I come to class B where I will call this method like the below:

class B {
    try {
        openfileConnect()
    }
    catch(Exception e) {
    }
}

I was asked a question in an interview as follows:

  1. Why does the method have a throws Exception in its declaration? Is it that on of the methods called in the implementation throws the base class exception?
  2. Also If we get a exception during calling the method (fileConnect( )) control goes to catch block. After executing catch where should the control go, what should be sent to base case?

Can any one help me in sorting out this issue? Thanks in Advance.

A: 

The method openfileConnec() has a throws declaration since opening files can throw an IOException (if file doesn't exist, or is not readable for example).

If this exception is not managed in the method, the method must declare that the exception is thrown.

Benoit Courtine
+1  A: 

I was asked a question in an interview as follows: Why does the method have a throws Exception in its declaration?

because it wants to tell method invoker that something is wrong and method invoker should decide what to do with this problem (Exception).

Is it that on of the methods called in the implementation throws the base class exception?

this is also true, but a method can decide to throw new Exception itself. because it want to let caller decide abut the issue not itself.

After executing catch where should the control go, what should be sent to base case?

its up to invoker that how it wants to handle the error. (e.g. show error message and inform user or do another action) its up to invoker.

mohammad shamsi