Java Reference
In-Depth Information
Applicability
Cyclic dependencies between packages can result in fragile builds. A security vulnerabil-
ity in a package can easily percolate to other packages.
Bibliography
[Allen 2000]
The Elements of Java Style
[Havelund 2009]
JPL Coding Standard, Version 1.1
[Knoernschild 2002]
Chapter 1, “OO Principles and Patterns”
33. Prefer user-defined exceptions over more general exception types
Because an exception is caught by its type, it is better to define exceptions for specific
purposes than to use general exception types for multiple purposes. Throwing general ex-
ception types makes code hard to understand and maintain, and defeats much of the ad-
vantage of the Java exception-handling mechanism.
Noncompliant Code Example
This noncompliant code example attempts to distinguish between different exceptional
behaviors by looking at the exception's message:
If doSomething() throwsanexceptionorerrorwhosetypeisasubclassof Throwable ,
the switch statement allows selection of a specific case to execute. For example, if the ex-
ception message is “file not found,” the appropriate action is taken in the exception-hand-
ling code.
Click here to view code image
try {
doSomething();
} catch (Throwable e) {
String msg = e.getMessage();
switch (msg) {
case "file not found":
// Handle error
break;
case "connection timeout":
// Handle error
Search WWH ::




Custom Search