throws tells others that this method can throw an exception. Think of it as documentation. Checked exceptions must be part of a method's signature.
throw actually throws the exception. (throw new Exception(); first creates a new exception instance and then throws that instance. You could use two separate statements: Exception ex = new Exception(); throw ex;) You can throw both checked and unchecked exceptions with the throw keyword.
void checked() throws Exception { // required, Exception is a checked exception
throw new Exception();
}
void unchecked() {
throw new RuntimeException(); // throws not required, RuntimeException is not checked
}
void checkedCall() throws Exception {
checked(); // throws required, because "checked" can throw a checked exception
}
void caught() {
try {
checked();
} catch (final Exception ex) {
// throws is no longer required, because the (checked) exception is handled within the method itself. It never leaves the method.
}
}
Regarding your updated question: you don't throw new ArithmeticException, because it is thrown by the JVM when it tries to apply the / operator. You can throw it manually if you want to, but that's just redundant code.
JAVA throws and throw?
ELI5: The difference between "throws" and "throw"
Try/Catch vs Throws?
Throwing an exception and catching it within the same method? Is this bad practice?
Videos
Hey,
so what is the use of the keyword „throws“? I found in several sources something like this:
„Throws keyword can be placed in the method declaration. It denotes which exceptions can be thrown from this method.“
But why cant i just make a comment and say: // this and this exception might be thrown
I dont really know why this was implemented? There must be something i clearly didnt understand