Question

I am looking into some exception one method is throwing. The method looks like this:

public void someMethod() throws someCheckedException{

  //doSomething statements
  //but no statements actually throws 'someCheckedException'

}

My question is that is it possible to make this method throw 'someCheckedException' while the implementation does not have a throw statement at all.

Is it wrong to put throw exception in signature without implement a statement throwing exceptions?

Was it helpful?

Solution

This is completely fine. The throw statement in method signature is there in case method throws actual exception declared in the throws statement and to usually pass handling to different class You just need to remember to put such method into try catch statement when you want to use it.

OTHER TIPS

The exception is probably thrown by one of the methods called by someMethod.

e.g.

    void method1() throws Exception {
        method2();
    }

    void method2() {
        throw new Exception();
    }

It's legal. This is very commonly done in RMI. The methods in the remote interface must be declared to throw RemoteException, but the implementation methods don't need to declare it, as they don't actually throw it themselves (unless they do RMI calls of their own). The remote exceptions are thrown by RMI itself. However they are frequently declared to do so just to agree with the remote interface. It's not necessary.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top