本文介绍了推荐的方法来处理算法中的问题/错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

保持堆栈跟踪,让我们说,'错误'的想法是一个你不想发生的问题,但是这样做。



如果我是使用一个布尔系统来检查操作是否成功完成,它看起来像这样:

  String [] array = new String [10]; 
int i = 0;

public boolean accessValue(int id){
if(id // do something
return true;
}
返回false;
}

while(true){
if(!accessValue(i ++)){
//倾向于情况
}
}

如果我使用例外,它将如下所示:

  class InvalidAccessException extends Throwable {

}

public boolean accessValue(int id)throws InvalidAccessException {
if(!id throw new InvalidAccessException();

//做某事
}

while(true){
try {
accessValue(i ++);
} catch(InvalidAccessException e){
//趋向于
}
}

对我来说唯一重要的是当发生问题时,我以某种方式通知,我将有一个选项来处理这种情况。哪种方式更实践?这是否取决于情况,还是有原因选择一个?

解决方案

你提到的第一种方法,更多的是 C ,其中您有函数产生各种整数,以表示函数在执行过程中如何公平。



虽然这个工作它(在我看来)引入了额外的问题,开发人员需要通过其他文档或其他开发人员代码来理解为什么返回特定值。



在Java中,据我所知,出现错误的时候总是会抛出异常(即使你希望它出错)。使用异常的明显优点是代码更易于阅读,只要看到您的方法签名即可知道您的方法可能导致什么潜在问题。这将允许我更快地编码,因为我不需要挖掘自己的文档或代码只是来查看你的方法的行为(尽管我可能需要挖掘文档/代码看看我是否可以找到一个解决方案,为什么是你的代码抛出异常)。



另外,由于Java没有一个元组的实现返回您需要创建自己的错误代码和值,这些错误代码和值可能会影响代码的可用性和可读性,这在我看来总是应该避免的。



编辑:

Yes it should since exception handling will allow you handle exceptional events, so in your code, you could have this:

while(true) {
     try {
          accessValue(i++);
     }catch(InvalidAccessException e) {
          //Execute algorithms here
     }
}

Having a stack trace is helpful when, as you are saying, you are debugging a problem since it provides information of which methods where called when your program crashed. That being said, they are not the only benefit of using exceptions (as mentioned above).

Another potential problem I see with using return values is when different developers work on the same function. So you could have something like so designed by one developer:

function int doSomething()
{
     //if it worked, yield 0
     //else yield some number between 1 and 10
}

Then another developer comes along which believes that errors should have negative numbers and extends the above method,

function int doSomething()
{
     //if it worked, yield 0
     //else yield some number between 1 and 10
     //something else went wrong, return -1
}

The above would mean that you would need to go through all other functions calling doSomething() and see that they now handle the case where the return value is negative. This is cumbersome and is also error prone.

EDIT 2:

I hope I am getting your point. I see this issue when you return true/false:Assume this:

public boolean foo(arg1, arg2)
{
     if(arg1 is invalid) return false;
     if(arg2 is invalid) return false;
}

In the above example, what does false mean? Does it mean arg1 is invalid or arg2? What if you need to trigger different algorithms for different parameter validity?

这篇关于推荐的方法来处理算法中的问题/错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 03:15
查看更多