Exception Specification

2022-09-04 21:48:04

Does Exception specification is a part of method signature? What I mean is:

public void someMethod(String myString) throws IOException

is 'throws IOException' a part of a signature of this method?

Thanks


答案 1

Following up on Jon Skeet's answer and in response to the comment

@ Jon Skeet Why then I cant have public void run() throws IOException in a class which implements Runnable? – Knowing me knowing you

Section 8.4.6 of the Java Language Specification (3rd ed) says:

A method that overrides or hides another method (Section 8.4.8), including methods that implement methods defined in interfaces, may not be declared to throw more checked exceptions than the overridden or hidden method.abstract

More precisely, suppose that B is a class or interface, and A is a superclass or superinterface of B, and a method declaration n in B overrides or hides a method declaration m in A. If n has a clause that mentions any checked exception types, then m must have a clause, and for every checked exception type listed in the clause of n, that same exception class or one of its supertypes must occur in the erasure of the clause of m; otherwise, a compile-time error occurs.throwsthrowsthrowsthrows

It's not a matter of method signature here, but a matter of not requiring callers to account for exceptions that aren't required to be checked by the 'original' method they are calling.


答案 2

No. From section 8.4.2 of the Java Language Spec:

Two methods have the same signature if they have the same name and argument types.

Two method or constructor declarations M and N have the same argument types if all of the following conditions hold:

They have the same number of formal parameters (possibly zero) They have the same number of type parameters (possibly zero) Let be the formal type parameters of M and let be the formal type parameters of N. After renaming each occurrence of a Bi in N's type to Ai the bounds of corresponding type variables and the argument types of M and N are the same.

So two methods with the same name and arguments but different declared exceptions, they have the same signature.

Furthermore, from the document Bozho quotes:

Definition: Two of the components of a method declaration comprise the method signature—the method's name and the parameter types.

No mention of exceptions there...

EDIT: As for overriding a method (or implementing an interface), from section 8.4.8.3:

A method declaration must not have a throws clause that conflicts (§8.4.6) with that of any method that it overrides or hides; otherwise, a compile-time error occurs.