Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Method Signature Throws Exception, Implementation does not [closed]

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?

like image 718
Xiu Avatar asked Sep 24 '26 14:09

Xiu


2 Answers

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.

like image 99
MrCurious Avatar answered Sep 26 '26 03:09

MrCurious


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();
    }
like image 44
Mosterd Avatar answered Sep 26 '26 04:09

Mosterd