在 Java 中抛出异常的链表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2203030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 20:01:39  来源:igfitidea点击:

Throwing a Linked List of Exceptions in Java

javaexception-handling

提问by Daniel Bingham

I have a function that loops while doing something that could throw an exception. Looks something like this:

我有一个在执行可能引发异常的操作时循环的函数。看起来像这样:

public void myFunction() throws MyException {
    while(stuff) {
        try {
            DoSomething() // throws an exception
        }
        catch (Exception ex) {
            throw new MyException(some, stuff, of, mine, ex);
        }
    }
}

The error causing the exception is recoverable. It can be something like an SQL error in a single update statement where the while loop executes a series of update statements. Or a parsing error in a single piece of data, where the loop is processing multiple pieces of data. I need to pass the exception further up the chain so the GUI part of the program can process it, handle it and pass on the error to the user. But I don't want to kill the loop in this particular function. The other things it's doing might not be invalid. The error that caused the exception might not be fatal to the function.

导致异常的错误是可恢复的。它可能类似于单个更新语句中的 SQL 错误,其中 while 循环执行一系列更新语句。或者单个数据中的解析错误,其中循环正在处理多个数据。我需要将异常进一步向上传递,以便程序的 GUI 部分可以处理它,处理它并将错误传递给用户。但我不想终止这个特定函数中的循环。它正在做的其他事情可能不是无效的。导致异常的错误可能对函数来说不是致命的。

So my question is this: Is it an acceptable practice to build linked lists of custom exceptions (where each exception is a node, and the exception thrown is the head of the list) and then throw the head of the list (if any) once the loop finishes?

所以我的问题是这样的: 构建自定义异常的链表(其中每个异常是一个节点,抛出的异常是列表的头部)然后抛出列表的头部(如果有的话)一次是否可以接受循环结束?

Has anyone ever seen this done? Can anyone think of any potential problems with doing this? Can anyone think of other, better ways to handle the root problem: the need to pass up multiple unrelated exceptions with out exiting the function until it is done?

有没有人见过这样做?任何人都可以想到这样做的任何潜在问题吗?谁能想到其他更好的方法来处理根本问题:需要传递多个不相关的异常而不退出函数直到它完成?

Here's an example of how the linking and throw might be implemented very simply:

这是一个如何非常简单地实现链接和抛出的示例:

public void myFunction() throws MyException {
    MyException head = null;
    while(stuff) {
        try {
            DoSomething() // throws an exception
        }
        catch (Exception ex) {
            MyException tmp = new MyException(some, stuff, of, mine, ex);
            tmp.next(head);
            head = tmp;
        }
    }
    if(head != null)
       throw head;
}

采纳答案by Brian Agnew

My intial thought (other than I've not seen this) is that an exception is potentially quite a large object (containing the stacktrace) and I'd prefer notto store a lot of them.

我INTIAL想法(除了我还没有看到这一点)是一个例外是潜在的(含堆栈跟踪)相当大的对象,我宁愿来存储他们中的很多。

I would instead build a list of the erroneous parameters/arguments as exceptions occur, and upon completion of the loop, throw a custom exception populated with this list (if the list has more than 0 elements). That would seem a more manageable way of handling this scenario.

相反,我会在异常发生时构建一个错误参数/参数列表,并在循环完成后,抛出一个填充了该列表的自定义异常(如果该列表有 0 个以上的元素)。这似乎是处理这种情况的一种更易于管理的方式。

public void myFunction() throws CustomException {
    List<MyError> errors = new ArrayList<MyError>();
    while(stuff) {
        try {
            DoSomething() // throws an exception
        }
        catch (Exception ex) {
            errors.add(new MyError(some, stuff, of, mine, ex));
        }
    }
    if (errors.size() > 0) {
       throw new CustomException(errors);
    }
}

回答by Kevin

Do you really need to throw all the exceptions? How do you expect to the individual, unrelated exceptions to be handled? Generally in cases like this, the system will just report the errors and be done with it.

你真的需要抛出所有的异常吗?您希望如何处理个别的、不相关的异常?通常在这种情况下,系统只会报告错误并完成处理。

If so, you might want to just collect the error messages and add them to a custom Exceptionclass and throw that.

如果是这样,您可能只想收集错误消息并将它们添加到自定义Exception类中并抛出它。

回答by BalusC

If those exceptions are really unrelated to each other so that you can't take benefit of get/setCause(), then I would rather collect this information in one MyException.

如果这些异常确实彼此无关以至于您无法从中受益get/setCause(),那么我宁愿将这些信息收集在一个MyException.

E.g.

例如

public void myFunction() throws MyException {
    MyException myException = null;
    while(stuff) {
        try {
            DoSomething() // throws an exception
        }
        catch (Exception ex) {
            if (myException == null) {
                myException = new MyException();
            }
            myException.addException(some, stuff, of, mine, ex);
        }
    }
    if (myException != null) {
        throw myException;
    }
}

Update:Brianhandles exactly this approach in a more neat manner. I would opt for that instead :)

更新:Brian以更简洁的方式处理这种方法。我会选择那个:)

回答by x4u

Actually throwing any exceptions from such a function is probably not the right way to handle this if it is expected that there will be errors. I'd suggest to either return a List (Array) of all exceptions/errors that occured or better to provide a error handler object to the function that can deal with the exceptions. i.e.:

实际上,如果预计会出现错误,则从此类函数中抛出任何异常可能不是处理此问题的正确方法。我建议要么返回发生的所有异常/错误的列表(数组),要么更好地为可以处理异常的函数提供错误处理程序对象。IE:

public interface ErrorHandler
{
    public void handleError( Throwable ex /*, add some context info */ );
}

public void myFunction( ErrorHandler eh )
{   
    while(stuff) {   
        try {   
            DoSomething() // throws an exception   
        }   
        catch (Exception ex) {
            if( eh != null )
                eh.handleError( ex );
        }   
    }   
}   

This also lets the error handler either collect the errors to present them to the user or to decide that the whole batch operation has become void because of some error and to throw a exception of it's own to abort the processing early.

这还允许错误处理程序收集错误以将它们呈现给用户,或者决定整个批处理操作由于某些错误而无效并抛出它自己的异常以提前中止处理。

回答by Dudaskank

I think you can pass some callback or listener to the method, or set in a class variable and instead of a throw the list, like x4u did.

我认为您可以将一些回调或侦听器传递给该方法,或者在类变量中进行设置,而不是像 x4u 那样抛出列表。

In Java there is an interface for this already: java.beans.ExceptionListener

在 Java 中已经有一个接口: java.beans.ExceptionListener

回答by Erkan Haspulat

If the exception thrown by DoSomething();could cause the very same method to throw another exception; this might be a problem. In other words, if DoSomething();throws an exception becauseyou didn't handle the previous one, there might be unnecesarry error to handle.

如果抛出的异常DoSomething();可能导致相同的方法抛出另一个异常;这可能是个问题。换句话说,如果由于您没有处理前一个DoSomething();引发异常,则可能会有不必要的错误需要处理。

回答by Carlos Blanco

IMO, an exception should be the last resource you have for handling an error. It should be avoided if possible. So, you might want to pass the error description (create error codes, pass the message, or something meaningful) to the GUI, and not the exception itself.

IMO,异常应该是您处理错误的最后一个资源。如果可能,应该避免。因此,您可能希望将错误描述(创建错误代码、传递消息或其他有意义的内容)传递给 GUI,而不是异常本身。