Question
What is the difference throw and throws?
Answer
throws: Used in a method’s signature if a method is capable of causing an exception that it does not handle, so that callers of the method can guard themselves against that exception. If a method is declared as throwing a particular class of exceptions, then any other method that calls it must either have a try-catch clause to handle that exception or must be declared to throw that exception (or its superclass) itself. A method that does not handle an exception it throws has to announce this: public void myfunc(int arg) throws MyException {
} throw:Used to trigger an exception. The exception will be caught by the nearest try-catch clause that can catch that type of exception. The flow of execution stops immediately after the throw statement; any subsequent statements are not executed. To throw an user-defined exception within a block, we use the throw command:
throw new MyException("I always wanted to throw an exception!");