In Java, you need to specify how your method behaves. This includes exceptions that can possibly be thrown. To declare, that you method can that an exception, the throws
keyword is used (as in your first Example).
Note that only Exceptions that derive from the Exception
class must be depicted here (there are also RuntimeExceptions
and other Throwables
that do not need to be depicted. More here).
To throw an Exception you need the keyword throw
followed by the instance of any Exception
(to be precise, you can throw any Throwable
).
A valid method would be:
public void foo() throws Exception {
throw new Exception();
}
solved Throwing exceptions two attitudes [duplicate]