-2

For example in this method : protected void doPost(HttpServletRequest req,HttpServletResponse resp)throws ServletException,java.io.IOException {}

throw new ServletException,java.io.IOException ; is not being used in the method definition . why is that ? can anyone please tell me why? I'm new to java .

in the below code throw is used and why is it not used in the above method which throws exception.

  class SomeClassName { 
        void show() throws Exception
           {
            throw new Exception();
            }
         }
SabaRish
  • 105
  • 11
  • 3
    throw and throws are two different things. Google them – Eran Feb 10 '15 at 06:41
  • It's not explicitly throwing `ServletException` but it calls other methods which does. – Nir Alfasi Feb 10 '15 at 06:42
  • some reading: http://stackoverflow.com/questions/4392446/when-to-use-throws-in-a-java-method-declaration –  Feb 10 '15 at 06:45
  • Same reason we write `public int getNumberOfCats() {` instead of `public return 1; getNumberOfCats() {` – user253751 Feb 10 '15 at 06:58
  • My question is why throw is not used inside that throws method ?? . So what is the purpose of writing throws if it cant throw an exception? – SabaRish Feb 10 '15 at 07:39

3 Answers3

2

throws Exception and throw new Exception(); do completely different things.

throws Exception is part of the method signature, and specifies that "this method is allowed to throw Exceptions".

throw new Exception(); is a statement that actually throws an exception.

This is not valid (since throw can't be part of a method signature):

public void test() throw new Exception(); {
}

and nor is this (since throws Exception isn't a statement):

public void test() {
    throws Exception;
}
user253751
  • 57,427
  • 7
  • 48
  • 90
1

Literally, 'throws' itself means that it shall be associated with a behavior. 'throw' means that it shall be associated with an action.

Similarly, throws as a behavior is associated with a method signature.

public void test() throws CutomException{
    //do whatever
    throw new CustomException
}

The aforementioned method has a trait of throwing CustomException (throws), if triggered within method body to do the same (throw).

Ankur Piyush
  • 308
  • 1
  • 9
0

throw new Exception "creates" an exception, whereas throws Exception simply "throws" any encountered exceptions to the caller method.

MeetTitan
  • 3,383
  • 1
  • 13
  • 26