Exception Specification

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

Upvotes: 13

Views: 4068

Answers (2)

Anonymoose
Anonymoose

Reputation: 5982

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 abstract methods defined in interfaces, may not be declared to throw more checked exceptions than the overridden or hidden method.

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 throws clause that mentions any checked exception types, then m must have a throws clause, and for every checked exception type listed in the throws clause of n, that same exception class or one of its supertypes must occur in the erasure of the throws clause of m; otherwise, a compile-time error occurs.

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.

Upvotes: 7

Jon Skeet
Jon Skeet

Reputation: 1499880

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.

Upvotes: 5

Related Questions