异常处理:如果条件与异常 [英] Exception handling: If condition versus Exception

查看:64
本文介绍了异常处理:如果条件与异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为验证参数的有效性,C语言使用了一堆IF Else条件确定其是否有效。在JAVA中,它具有Exception工具来处理此问题。这两种方法的用途是什么,这两种方法的利弊是什么?谢谢!

To verify the validity of a parameter, C language uses a bunch of IF Else conditions to determine if it is valid. In JAVA, it has Exception facility to handle this. What's usage of these two method, what's the pros and cons of these two way? Thanks!

致谢!

推荐答案

我个人而言,我喜欢assert语句。

Personally, i like assert statement.

但是在这种情况下,对于复杂的问题,我更喜欢使用Try-Catch;对于较简单的问题,我更喜欢使用if-else。

But in this context, i prefer Try-Catch for complex problems and if-else for simpler problems.

if-else在很多情况下都不可读和不可维护,尤其是对于复杂的问题。这就是为什么try-catch可以解救。假设给定的输入正确,让我们对其进行处理。当某些行中的给定输入被证明不正确时,只需转到catch块并返回一些默认值即可。

If-else(s) aren't readable and maintainable where there are many of them, especially for complex problem. This is why try-catch comes to rescue. Assuming given input is correct, let's process it. When in some lines the given input proved incorrect, just go to catch block and returns some default value.

有人认为try-catch速度较慢。是的,这是真的。但是慢了多少? 0.1毫秒? 1毫秒?我会牺牲这些毫秒来提高可读性和可维护性。

It's argued that try-catch is slower. Well, it's true. But how much slower? 0.1 ms? 1 ms? I will sacrifice these miliseconds for readability and maintainability.

毕竟,在编程中,每个函数/过程都有前提条件。我们都知道先决条件是什么。最好的方法(根据我个人的观点)是断言所有参数都适合所有前提条件。这样,我们可以假定给定的输入总是正确的,因为另一层的伙伴已经保证了这一点。

After all, in programming, there are preconditions for every function/procedure. We all know what precondition means. The best way (my personal opinion) is to assert that all parameters fit all preconditions. This way we can assume that given input is always correct since mates in another floor already guarantee that.

这篇关于异常处理:如果条件与异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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