为什么要使用异常而不是if ... else [英] Why use an exception instead of if...else

查看:182
本文介绍了为什么要使用异常而不是if ... else的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,在数组索引超出限制"的情况下,为什么不提前检查数组长度:

For example, in the case of "The array index out of bound" exception, why don't we check the array length in advance:

 if(array.length < countNum)
 {
 //logic
 }
 else
 {
 //replace using exception
}

我的问题是,为什么选择使用异常?以及何时使用异常,而不是if-else

My question is, why choose to use an exception? and when to use an exception, instead of if-else

谢谢.

推荐答案

这取决于给定语言的可接受惯例.

It depends on acceptable practices for a given language.

在Java中,约定是始终在可能的情况下始终检查条件,并且不要在流控制中使用异常.但是,例如,在Python中,不仅以这种方式使用异常是可以接受的,而且这也是一种首选做法.

In Java, the convention is to always check conditions whenever possible and not to use exceptions for flow control. But, for example, in Python not only using exception in this manner is acceptable, but it is also a preferred practice.

这篇关于为什么要使用异常而不是if ... else的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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