何时在Java中使用异常(示例) [英] When to use exceptions in Java (example)

查看:127
本文介绍了何时在Java中使用异常(示例)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是不好的做法,虽然我知道我无法解释为什么。

I know that this would be bad practice although I know that I would not be able to explain why.

int [] intArr = ...
...
try{
   int i = 0;
   while(true){
      System.out.println(intArr[i++]);
   }
}catch(ArrayIndexOutOfBoundsException e){}

我认为你只应该对不应该发生的事情使用异常。我在问这个问题,因为我认为我有时会使用异常。如果您的编程正在运行标准情况应该抛出异常?

I think that you are only supposed to use exceptions for things that shouldn't happen. I am asking this question because I think that I am using exceptions wrong sometimes. If your programming is running a standard case should exceptions be thrown?

这似乎是相关的:
防止异常与捕获Java中的异常

推荐答案

您是对的:异常是为,ehm,例外案例。使用它们来控制正常的控制流程不仅掩盖了代码的意图(这将足以取消它的资格),而且还要慢得多,因为抛出和捕获异常是昂贵的。

You are right: exceptions are meant for, ehm, exceptional cases. Using them for controlling normal control flow is not only obscuring the intent of the code (which would be enough to disqualify it already), but also is much slower, since throwing and catching exceptions is costly.

标准成语(在Java5及更高版本中)正在使用 foreach 循环:

The standard idiom (in Java5 and above) is using a foreach loop:

for (int i : intArr) {
  System.out.println(i);
}

这篇关于何时在Java中使用异常(示例)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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