简体   繁体   English

向后传播异常,并继续执行Java中的执行流程

[英]Propagating the exception back and continue with the execution flow in java

I have a scenario where i am processing a list of packages. 我有一个正在处理软件包列表的场景。 In this packages list there are some valid packages and some are invalid packages.Currently what i am doing is finding the invalid packages and wrapping it in an exception and throwing it back. 在此软件包列表中,有一些有效的软件包和一些无效的软件包。当前我正在做的是查找无效的软件包并将其包装在异常中并将其扔回。 But in this case i am not able to figures out how to continue with the flow of valid packages. 但是在这种情况下,我无法弄清楚如何继续进行有效的包装流程。 Is there anyway in which i can propagate the exception back where i can process it and at the same time continue with the processing with the valid packages. 无论如何,我可以将异常传播回我可以对其进行处理的地方,同时继续使用有效的软件包进行处理。 Is it possible to achieve it using java ? 是否可以使用Java实现呢?

You probably shouldn't use an exception in this case, since an invalid package is an expected situation, and not an exceptional one. 在这种情况下,您可能不应该使用异常,因为无效的软件包是一种预期的情况,而不是例外的情况。 I would simply use a return value. 我只是使用一个返回值。 But the following technique could be used with an exception as well if you really want to keep it that way: 但是,如果您确实想保持这种方式,还可以使用以下技术作为例外:

/**
 * processes all the packages and returns the invalid ones
 */ 
public List<Package> processPackages() {
    List<Package> invalidPackages = new ArrayList<>();
    for (Package package: allPackages) {
        if (isInvalid(package)) {
            invalidPackages.add(package);
        }
        else {
            processPackage(package);
        }
    }
    return invalidPackages;
}

With an exception instead: 除了一个例外:

/**
 * processes all the packages
 * @throws InvalidPackagesFoundException if invalid packages were found. The thrown
 *         exception contains the invalid packages
 */ 
public void processPackages() throws InvalidPackagesFoundException{
    List<Package> invalidPackages = new ArrayList<>();
    for (Package package: allPackages) {
        if (isInvalid(package)) {
            invalidPackages.add(package);
        }
        else {
            processPackage(package);
        }
    }
    if (!invalidPackages.isEmpty()) {
        throw new InvalidPackagesFoundException(invalidPackages);
    }
}

If the goal is to let the caller handle an invalid package as soon as it is found, then you could pass an additional callback argument to your method: 如果目标是让调用者在发现无效包后立即对其进行处理,则可以将其他回调参数传递给方法:

/**
 * processes all the packages. Each invalid package found is sent to the given
 * invalid package handler.
 */ 
public void processPackages(InvalidPackageHandler invalidPackageHandler) {
    for (Package package: allPackages) {
        if (isInvalid(package)) {
            invalidPackageHandler.handle(package);
        }
        else {
            processPackage(package);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM