简体   繁体   中英

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 ?

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);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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