不如我舉個例子
假設我有一個parse function, 係 public Foo parse(String input);
咁當個input係古怪野, 我應該return null定throw ex?
我會prefer foo2做法, 因為foo1我要格硬拆個declaration出黎, 又要專登係個method declaration加throws statement
public void MyCaller() {
Foo foo1 = null;
try {
foo1 = parse1(this.str);
} catch (Exception ex) {
// handle, log error and return
}
Foo foo2 = parse2(this.str);
if (foo2 == null) {
// handle, log error and return
}
}
public Foo parse1(String input) throws Exception {
Foo ret = new Foo();
// do my parsing stuff...
int f1 = getF1(input);
if (f1 < 0) throw new Exception();
return ret;
}
public Foo parse2(String input) {
Foo ret = new Foo();
// do my stuff...
int f1 = getF1(input);
if (f1 < 0) return null;
return ret;
}