使用try / catch而不是多个IF语句更好吗? [英] Is it better to use try/catch instead of multiple IF statements?

查看:125
本文介绍了使用try / catch而不是多个IF语句更好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中使用 try / catch 块是否更好,更便宜或更具可读性,而不是使用多个如果例如检查用户输入的语句?

Is it better, less expensive or more readable to use a try/catch block in Java instead of using multiple If statements to check user input for example?

解析 Date 字符串时的示例,不是最好使用try / catch块直接解析,而不是编写多个查找非法字符的语句。

Example when parsing a Date string, won't it be better to parse directly using a try/catch block instead of writing multiple statements looking for illegal characters.

在另一个例子中,假设我想要读取文件或流,而不是使用 Scanner ,我只是强迫方法并等待发生异常。

In another example, say i want to read a file or stream, instead of using Scanner, I just force the method and wait for an exception to occur.

这是一种健康的编程方法吗?它是否在虚拟机上更便宜?

Is that a healthy method of programming? Is it less expensive on the Virtual Machine?

更新


这是我在使用DateFormat例外,有时候捕获错误可能是一个真正的问题,当这样做时,你能保证你的复杂(通常是不可读的)代码容易出错吗?

UPDATE
Here is an example of what i meant when using DateFormat exception, sometimes it could be a real problem to catch an error, and when doing so, can you guarantee your complicated (usually unreadable) code is error prone?

推荐答案

使用Exceptions进行流量控制是一种不好的做法。

It's a bad practice to use Exceptions for a flow control.

部分报价:


因为例外设计用于特殊$ b下的使用$ b情况,很少,如果有的话,JVM实现尝试
优化他们的性能。创建,
抛出和捕获异常通常很昂贵。

Because exceptions are designed for use under exceptional circumstances, few, if any, JVM implementations attempt to optimize their performance. It is generally expensive to create, throw, and catch an exception.


在存在无关错误的情况下,成语
可以无声地失败并掩盖错误,使调试
进程大大复杂化。

In the presence of an unrelated bug, the idiom can fail silently and mask the bug, greatly complicating the debugging process.

更新:
据说(我记得我在Josh Bloch的博客中也发现了相同的声明)使用了流量异常控制就像使用GOTO一样。你可以阅读有趣的Dijkstra文章,了解为什么GOTO是坏的。

Update: As it's said (and I remember that I also found the same statement in Josh Bloch's blog) using exceptions for flow control is like using GOTOs for the same purpose. You can read interesting Dijkstra article about why GOTOs are bad.

这篇关于使用try / catch而不是多个IF语句更好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆