为什么String.indexOf不使用异常但是在没有找到子字符串时返回-1? [英] Why String.indexOf do not use exception but return -1 when substring not found?

查看:267
本文介绍了为什么String.indexOf不使用异常但是在没有找到子字符串时返回-1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么String.indexOf不使用异常,但是当未找到子字符串时返回-1?



此问题的目的是:当我们启动自定义异常时。 p>

我相信避免需要返回特殊错误代码是正确的设计路径。



你的意见是什么? >

解决方案

作为一个经验法则,如果一个方法的目的是检查一些东西,那么缺乏这样的东西不应该一个例外。如果该方法假定某事物是真实的,则不存在该事物将是一个例外。因此,File.exists()不会抛出FileNotFoundException,而是File.open()。


Why String.indexOf do not use exception but return -1 when substring not found?

The purpose of this question is: when we start custom exception.

I believe avoid the need to return special error code is right design path.

What's your opinion?

解决方案

As a rule of thumb, if the purpose of a method is to check for something, then the lack of that something shouldn't be an exception. If the method is assuming that something is true, then the absence of that something would be an exception. Thus "File.exists()" doesn't throw a FileNotFoundException, but "File.open()" does.

这篇关于为什么String.indexOf不使用异常但是在没有找到子字符串时返回-1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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