Home > Java > javaTutorial > Item Use exceptions only in exceptional circumstances

Item Use exceptions only in exceptional circumstances

Susan Sarandon
Release: 2024-12-09 21:02:10
Original
934 people have browsed it

Item  Utilize as exceções somente em circunstâncias excepcionais

Avoid using exceptions for common flow control:

Exceptions should only be used for unexpected situations, not to control the flow of a program.

Problematic code example: trying to use an exception to end a loop when exceeding the limits of an array.

try {
    int i = 0;
    while (true) {
        System.out.println(array[i++]);
    }
} catch (ArrayIndexOutOfBoundsException e) {
    // Este código encerra o loop quando o índice ultrapassa o tamanho do array
}

Copy after login

Problems: This use of exceptions is inefficient and confusing. It is better to use a suitable loop structure.

for (int i = 0; i < array.length; i++) {
    System.out.println(array[i]);
}

Copy after login

API Design Implications:

A well-designed API should avoid forcing the use of exceptions into the normal flow.

Example: The Iterator interface provides the hasNext() method to check for more elements, avoiding unnecessary exceptions when calling next().

Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}

Copy after login

Alternatives to state-dependent methods:

Provide a separate method to test the state (hasNext) or a special return value, such as null or an Optional, when the expected state cannot be met.

The above is the detailed content of Item Use exceptions only in exceptional circumstances. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template