I am trying to make it clear of the difference between Throws in method signature and Throw Statements in Java. Throws in method signature is a
throw
attribute in method signature, like you correctly guessed, is a hint to the compiler that the method raises an exception that must be caught by the caller. This kind of exception, namely called checked exception is something that the caller MUST always catch or dispatch to its caller again. This is something at compiler level, the signature specifies which exception the method is able to throw: this enforces a try-catch
or re-dispatch in the caller and a throw statement somewhere inside the method, is a constraint that the developer places to specify something about the method behavior.
On the other hand other exceptions, namely unchecked or runtime exceptions, (NoSucheElementException
is one example) are exceptions which you are not forced to specify becuase they arise from different situations.
The conceptual difference is that checked exception are usually used to warn about exceptional situation which should be handled somehow (think about IOException
) by the developer, while unchecked are real errors (like NullPointerException
or like in your example NoSuchElementException
)