Skip to content

Documentation Comments Style Guide - Background on the Throws Clause #19929

@gianmarcoschifone

Description

@gianmarcoschifone

Parent issue: #19807

Coverage table

Chapter link

Content

Image

Image

Text

Background on the Throws Clause

Checked exceptions must be included in a throws clause of the method. This is necessary for the compiler to know which exceptions to check. For example (in java.lang.Class):

public static Class forName(String className)
throws ClassNotFoundException

By convention, unchecked exceptions should not be included in a throws clause. (Including them is considered to be poor programming practice. The compiler treats them as comments, and does no checking on them.) The following is poor code -- since the exception is a RuntimeException, it should be documented in the @throws tag instead.

java.lang.Byte source code:

public static Byte valueOf(String s, int radix) 
throws NumberFormatException

Note that the Java Language Specification also shows unchecked exceptions in throws clauses (as follows). Using the throws clause for unchecked exceptions in the spec is merely a device meant to indicate this exception is part of the contract between the caller and implementor. The following is an example of this (where "final" and "synchronization" are removed to make the comparison simpler).

java.util.Vector source code:

public Object elementAt(int index)

java.util.Vector spec in the Java Language Specification, 1st Ed. (p. 656):

public Object elementAt(int index)
throws IndexOutOfBoundsException

Guidelines

unchecked exceptions should not be included in a throws clause

We can't be sure whether this is satisfied.
Proposal:

Documentation Comments Rule Checkstyle Checks Used Sample files
Background on the Throws Clause 🚫Violations of this guideline cannot be detected by Checkstyle due to its limitation, the complete inheritance hierarchy of a type cannot be determined.
Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions