如何在Java中進行除Java之外的其他嘗試?Java如何做除Python以外的其他嘗試
例子:
try:
something()
except SomethingException,err:
print 'error'
else:
print 'succeeded'
我看到try和catch提及,但沒有別的。
如何在Java中進行除Java之外的其他嘗試?Java如何做除Python以外的其他嘗試
例子:
try:
something()
except SomethingException,err:
print 'error'
else:
print 'succeeded'
我看到try和catch提及,但沒有別的。
我並不完全相信我喜歡它,但這相當於Python的其他東西。它消除了將成功代碼放在try塊末尾的問題。
bool success = true;
try {
something();
} catch (Exception e) {
success = false;
// other exception handling
}
if (success) {
// equivalent of Python else goes here
}
雖然沒有內置的方法來做這件事。你可以做類似的事情來獲得類似的結果。評論解釋了爲什麼這不是完全相同的東西。
如果執行somethingThatCouldError()
通過,將打印YAY!!
。如果出現錯誤,將打印SAD
。
try {
somethingThatCouldError();
System.out.println("YAY!!");
// More general, code that needs to be executed in the case of success
} catch (Exception e) {
System.out.println("SAD");
// code for the failure case
}
這種方式比Python更不明顯。但它達到了同樣的效果。
關閉,但如果下面的代碼「YAY」拋出異常會怎麼樣?它會打印出「YAY」和「SAD」。 – 2010-08-13 15:26:44
@亞當,是。但是,您可以將'Yay'放在'try'的底部。 – jjnguy 2010-08-13 15:31:21
我的觀點是,即使'somethingThatCouldError()不會引發異常,異常處理程序也可以執行。我不認爲這正是格雷格想要的。我明白了,亞當, – 2010-08-13 15:33:09
這是怎麼回事?
try {
something();
} catch (Exception e) {
// exception handling
return;
}
// equivalent of Python else goes here
當然,也有一些情況下,你想要的try/catch/else和該解決方案不適合有後把更多的代碼,但它的作品,如果它在你的方法唯一的try/catch塊。
在許多情況下(例如小方法),您可以重新拋出或從'catch'塊返回,因此您可以在完成try-catch之後放置'else'邏輯。 – 2014-01-11 16:56:22
-1爲了複製Python'try-catch-else'構造的語義,你不應該使用finally塊,因爲即使'try'中有'return'或未被捕獲的異常,它也會被執行。塊。只需在'try-catch'後面加上'if(success)'塊即可。 – augurar 2014-07-07 17:49:59
Thanks @augurar - 我在其他地方玩過並重讀了其他文檔,你確實是對的。 – 2014-07-08 13:39:07