try catch 和 if 在处理程序可能的出错上有什么区别?

2019-06-24 15:04:13 +08:00
 aoscici2000

比如说抽取文章前 100 字作为简介, 两种方法有什么区别


String content = ".........."

try {
    content = content.substring(0, 100)
} catch (StringIndexOutOfBoundsException e) {
    // pass
}

if ( content.length() > 100 ) {
    content = content.substring(0, 100)
}

3985 次点击
所在节点    Java
26 条回复
zhangchioulin
2019-06-24 19:31:12 +08:00
LBYL
Look before you leap. This coding style explicitly tests for pre-conditions before making calls or lookups. This style contrasts with the EAFP approach and is characterized by the presence of many if statements.
In a multi-threaded environment, the LBYL approach can risk introducing a race condition between “ the looking ” and “ the leaping ”. For example, the code, if key in mapping: return mapping[key] can fail if another thread removes key from mapping after the test, but before the lookup. This issue can be solved with locks or by using the EAFP approach.

EAFP
Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

https://docs.python.org/3/glossary.html#term-eafp
leishi1313
2019-06-25 01:08:57 +08:00
我觉得 EAFP 虽然是种好的风格,但在楼主的例子里不是很适用。EAFP 更多地是用在处理程序外部资源的时候,比如文件,线程,网络等等,这时候用 try..catch 更安全也更普遍。
另外从 readability (可读性)角度来说,处理字符串 /数组越界之类的,明显 if 的可读性更好。用楼主的例子来说,这个函数的需求是截取文章前 100 字作为简介,天然地就会写成 if article.length() <=100 return article else article.substring(0, 100),简单明了,目的明确,写成 try catch 反而还要绕一个弯想一下什么时候会抛这个异常,然后才能明白程序的意图。
msg7086
2019-06-25 03:45:44 +08:00
@geelaw 网络访问假定失败这个假定和我说的假定还有些不同。
比如 TCP 协议是一个相对可靠的协议,那么程序员原本就应该假定这个协议是可靠的。TCP 协议出错(比如丢包过多或者被功夫认证)可以被认为是属于「异常」情况的。
而像 UDP 这样不可靠的报文协议,报文没有送达可以被认为属于正常情况。
geelaw
2019-06-25 04:07:37 +08:00
@msg7086 #23 我说的是断网
zw1one
2019-06-25 10:19:46 +08:00
catch 用来捕获难以避免的异常,尽量不要用 catch 来处理业务逻辑。有效率问题。
linuxsteam
2019-07-23 08:10:35 +08:00
@xiaopang132 你这是什么操作?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/576937

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX