Java适当处理异常 [英] Java dealing with exceptions appropriately

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

问题描述

不熟悉JAVA或异常处理。寻找一些关于什么是可接受的和什么是皱眉的建议。

not that familiar with JAVA or exception handling. Looking for some advice on what is acceptable and what is frowned upon.

这个场景,我正在建立一个生活游戏,我有条件设置来检查是否一个单元格将超出范围,而不是尝试访问该单元格。我的问题是,使用try catch块而不是8条件是可以接受的,如果抛出arrayOutOfBounds异常,只要不执行任何操作。即忽略细胞的界限,还是这个不好的做法?例如...

The scenario, i'm building a game of life program, I have conditionals set up to check if a cell will be out of bounds and not try to access that 'cell'. My question is, is it acceptable to use a try catch block instead of 8 conditionals, and just do nothing if the arrayOutOfBounds exception is thrown. ie ignore the cells out of bounds, or is this bad practice? for instance...

try{
    neighbors += cellIsAlive(row, col);
}catch(ArrayIndexOutofBoundsException e)
{
    //dont do anything and continue counting neighbors
}

在这种情况下,cellIsAlive方法检查多维数组中的位置,否则返回1,否则抛出ArrayIndexOutofBoundsException。

In this scenario cellIsAlive method checks a location in a multi dimensional array and returns 1 if it's alive 0 otherwise and throws ArrayIndexOutofBoundsException.

这是一个好主意,还是以这种方式使用异常是不好的做法?

Is this a good idea or is it bad practice to use exceptions this way?

提前感谢任何输入。

推荐答案

这绝对是一个不好的做法。异常处理消耗大量资源,只能用于特殊情况(如其名称所暗示的)。

It's absolutely a bad practice. Exception handling consumes a lot of resources and should be used only (as its name implies) for exceptional cases.

查看本书第9章(并阅读其余的可以):

Take a look at chapter 9 of this book (and also read the rest when you can):

http ://www.amazon.com/Effective-Java-Edition-Joshua-Bloch/dp/0321356683/

你会看到你'尝试做的非常类似于用于说明你不应该做什么的例子,我引用:

You'll see that what you're trying to do is very similar to the example used for illustrating what you're not supposed to do, and I quote:


有一天,如果你不幸,你可能会碰到一块像
这样的代码:

Someday, if you are unlucky, you may stumble across a piece of code that looks something like this:



// Horrible abuse of exceptions. Don't ever do this!
try {
    int i = 0;
    while(true)
        range[i++].climb();
} catch(ArrayIndexOutOfBoundsException e) {
}




这段代码做什么?检查并不是很明显,而且
这个理由不够用(项目55)。结果是一个
可怕的构想错误的成语,循环使用
数组的元素。

What does this code do? It’s not at all obvious from inspection, and that’s reason enough not to use it (Item 55). It turns out to be a horribly ill-conceived idiom for looping through the elements of an array.

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

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