はじめに
私は、例外の使用が間違っているという同僚の声明に深く感動しました。 その後、一連の説明が続きました。遅い、,い、非効率的、不便です。
この問題に関するHabrユーザーの意見を構造化する
ために、例外の使用に関する小さな
調査を公開しました。 このトピックは、例外に関する資料の完全な説明であると主張するものではなく、それらの使用領域にのみ影響することをすぐに言いたいと思います。
これは、開発中にエラーの最適化、またはより一般的な意味での時期尚早な最適化があるというステートメントに基づいています。 多くの人々は、時期尚早な最適化が悪いことを知っています。 しかし、エラーの最適化は新しいエラーにつながり、コードを複雑にし、コード全体を不安定にします。
簡単な例
発生するエラーのほとんどを説明できる2つの簡単な例を考えてみましょう。
Point readPoint() {
...
}
Points readPoints() {
...
}
, :
Point point = readPoint();
if (point != null) {
...
}
Points points = readPoints();
if (points != null) {
...
}
. . , , .
null, . , , null — , .
. . , , . .
:
Points points = readPoints();
for (Point point : points) {
...
}
, .
, :
Point readPoint() throws PointNotFoundException {
...
}
Points readPoints() throws CouldNotReadPointsException {
...
}
:
- PointNotFoundException — , ;
- CouldNotReadPointsException — , .
:
try {
Point point = readPoint();
...
} catch(PointNotFoudException ex) {
...
}
try {
Points points = readPoints();
for (Point point : points) {
...
}
} catch(CouldNotReadPointsException ex) {
...
}
-, , . .
. — . . . 99,9% ? , .
, , ?
. , . :
while (!queue.isEmpty()) {
Point point = queue.readPoint();
if (point != null) {
...
}
}
null , .
:
try {
while (!queue.isEmpty()) {
Point point = queue.readPoint();
...
}
} catch(PointNotFoudException ex) {
throw new QueueReadingException(ex);
}
, - :
try {
while (!queue.isEmpty()) {
processNextPoint();
}
} catch(PointNotFoudException ex) {
throw new QueueReadingException(ex);
}
void processNextPoint() throws PointNotFoudException {
Point point = queue.readPoint();
...
}
QueueReadingException? — ! ?
. , , , , (- ).
, , . . , , , . , .
, . 5 . 100 , 10% . , 100 , 50 . , ( 900 ).
, . - , . , . , . , , .
P. S. get- read. . , .
— (
). , . .