3 回答

TA貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以簡單地將標(biāo)志添加到您的異常中。
public class PackageFailedException extends Exception {
private final boolean minorProblem;
public PackageFailedException(String msg, boolean minorProblem) {
super(msg);
this.minorProblem = minorProblem;
}
public boolean isFlag() {
return this.flag;
}
}
然后您可以簡單地調(diào)用isMinorProblem()并決定是否忽略它。這里的假設(shè)是你可以在它被拋出時(shí)傳遞它。
但是,如果該標(biāo)志指示了一個(gè)完全不同的錯(cuò)誤情況,您可能希望完全考慮一個(gè)不同的Exception類,如果它是一個(gè)更特殊的情況,可能會(huì)擴(kuò)展它。PackageFailedException
public class MinorPackageFailedException extends PackageFailedException {
public MinorPackageFailedException(String msg) {
super(msg);
}
}
然后在您的代碼中:
try {
try {
doThePackageThing();
} catch (MinorPackageFailedException ex) {
//todo: you might want to log it somewhere, but we can continue
}
continueWithTheRestOfTheStuff();
} catch (PackageFailedException ex) {
//todo: this is more serious, we skip the continueWithTheRestOfTheStuff();
}

TA貢獻(xiàn)1875條經(jīng)驗(yàn) 獲得超5個(gè)贊
您有條件地創(chuàng)建異常,因此只有在適當(dāng)?shù)臅r(shí)候才會(huì)拋出它。
要么和/或您根據(jù)捕獲時(shí)的條件以不同的方式處理異常。
你不做的是讓異常決定它是否應(yīng)該存在,那就是瘋狂。

TA貢獻(xiàn)1812條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可以繼承您的 PackageFailedException,以創(chuàng)建如下邏輯:
public class IgnorablePackageFailedException extends PackageFailedException {
public IgnorablePackageFailedException(final String msg) {
super(msg);
}
}
然后,在您的代碼中,您可以拋出 PackageFailedException 或 IgnorablePackageFailedException。例如:
public static void method1() throws PackageFailedException {
throw new PackageFailedException("This exception must be handled");
}
public static void method2() throws PackageFailedException {
throw new IgnorablePackageFailedException("This exception can be ignored");
}
因此,您可以像這樣處理異常:
public static void main(final String[] args) {
try {
method1();
} catch (final PackageFailedException exception) {
System.err.println(exception.getMessage());
}
try {
method2();
} catch (final IgnorablePackageFailedException exception) {
System.out.println(exception.getMessage()); // Ignorable
} catch (final PackageFailedException exception) {
System.err.println(exception.getMessage());
}
}
添加回答
舉報(bào)