Writing a Library
Exception
- Always throw exception as early as possible.
// DO
class Animal{
static final String name;
static {
name = LoadNameFromDisk()
if (name == null) {
throw IllegalStateException("Can not read name from disk"); // Throw exception here
}
}
public Animal(){}
}
// DON'T
class Animal{
static final String name = LoadNameFromDisk()
public Animal(){
if (name == null) {
throw IllegalStateException("Can not read name from disk"); // Too late to throw exception. Should throw it at installation time.
}
}
2. Hide detailed implementation exception from the upper caller. Always throw meaningful exceptions to caller (client)
// DO
class Animal{
static final String name;
static {
name = LoadNameFromDisk()
if (name == null) {
throw IllegalStateException("Can not read name from disk"); // Throw exception here
}
}
public Animal(){}
}
// DON'T
class Animal{
static final String name;
static {
name = LoadNameFromDisk()
if (name == null) {
throw NullPointerException("name is null"); // This is implementation detail. Should be hid from caller.
}
}
public Animal(){}
}
IllegalArgumentException: the argument the caller passed to the library is incorrect.
IllegalStateException: something wrong with the internal library implementation.