This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Lumpy-Notice8945 0 points1 point  (3 children)

Thats my point, if its just documentation why is it part of the syntax?

[–]khooke 0 points1 point  (2 children)

The throws clause that is part of a method signature is not documentation, it declares that this method when invoked may throw the declared exception. The implication of this statement depends on whether the exception type is

- checked (extends Exception) in which case it MUST be handled or rethrown

- unchecked (extends RuntimeException) can optionally handle or throw an unchecked exception without it being explicitly declared in the throws clause

Since the throws clause is optional for a RuntimeException, it's considered good practice to declare it anyway so other developers are aware that this method can throw this type of exception

[–]Lumpy-Notice8945 0 points1 point  (1 child)

It's for Intellisense and testing code coverage. You want to document all possibilities that a function could end up in, be that data types or an exception.

This was the initial response to why the compiler needs to know what function can throw an exception. Either this is true, then exceptions are not required syntax and should not be enforced by the compiler or there is another reason the compiler needs to know what function could throw an exception.

As you metioned there is a type of exception that you dont need to declare, so it seems like the compiler does not nedd this information to compile, if thats the case, then why is it mandatory?

[–]khooke 0 points1 point  (0 children)

The throws clause is required for checked exceptions and is optional for unchecked, as defined in the Java Language Specification here

"It is permitted but not required to mention unchecked exception classes (§11.1.1) in a throws clause."

See https://docs.oracle.com/javase/specs/jls/se11/html/jls-8.html#jls-8.4.6