What is the role of “throws exeption”
It's used for checked exceptions.
The idea is, if you write code to call a function that
throws FoobarException, then the compiler will force you to either handle the exception, or to add the same
throws FoobarException declaration to the function that you are writing.
It's a way to make sure that nobody will forget that a
FoobarException might be thrown.
This stub doesn't attempt to return an int. Instead it throws exception right away. Yet, IDE accepts it as a valid syntax. The program compiles and runs.
Checked exceptions turn out not to be as popular as the language designers had hoped. In fact, they anticipated that when they created a whole category of unchecked exceptions.
UnsupportedOperationException is an unchecked exception. Unchecked exceptions work exactly the same as checked exceptions. The only difference is that you are not required to declare the exception when you write a method that could throw it. Every exception that inherits from
java.lang.RuntimeException is unchecked.
The idea is, you're supposed to use checked exceptions for conditions that your program ought to handle in some graceful way (e.g., inform the user about a file-not-found instead of just crashing), and only use unchecked for exceptions that "can't possibly happen" unless your program is broken.
Is throw new UnsupportedOperationException considered a valid return for any return type?
No, it's not a "return", it's an exception. The compiler doesn't mind that your method never returns an
int, because the compiler can tell that your method never returns at all.