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 }
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]); }
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()); }
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!