I don't fully understand what the throws
keyword in Java is for.
In particular, I can't seem to find clear information about what happens if I were to throw an exception type T
from a Java function which declares that only exceptions of type Y
can be thrown.
For example, something like this:
void testFunction () throws SomeExceptionType {
throw new SomeDifferentExceptionType();
}
In this case I have attempted to illustrate that the expected exception type does not match the exception type which is actually thrown. Is this syntactically legal Java? If so, what happens at runtime?
I come from a C++ background, and in C++ we have the concept of noexcept
. This keyword is used to mark functions as noexcept
which means that they are not permitted to throw an exception. If a function marked noexcept
does throw an exception, then std::terminate
is immediately called, which borks program execution.
std::terminate
is effectively like a "goto" statement in that it takes you to the end of program execution, quitting the program runtime. It may also do some stack clean-up for RAII, this is actually implementation defined, apparently.
So, is Java's throws
statement equivalent to C++ noexcept
, but inverted?
Although there are lots of questions here which ask how to use throws
, I haven't been able to find a clear answer to this specific question about what happens if you throw something different to the exception type specified with throws
.
Edit: I understand that this is only really relevant to the concept of checked exception types, because unchecked exception types "do not interact with" the throws
keyword. Knowing this doesn't however provide an answer to the question being asked.