使用jdk 8处理异常

时间:2015-06-11 08:05:57

标签: java c#

我在C#中使用委托来处理我的异常:

public void QueryIpRanges(Action<ObservableCollection<LocationRange>, Exception> callback)
        {
            try
            {
                var ranges = from e in _xml.Descendants("computer")
                    select new LocationRange
                    {
                        Name = e.Attribute("prefix").Value,
                        Addresses = new ObservableCollection<IpRange>(
                            from i in e.Descendants("range")
                            select new IpRange
                            {
                                Start = i.Element("start").Value,
                                End = i.Element("end").Value,
                                Subnet = i.Element("subnet").Value,
                                Gateway = i.Element("gateway").Value
                            })
                    };

                callback(new ObservableCollection<LocationRange>(ranges), null);
            }
            catch (FormatException ex)
            {
                callback(null, ex);
            }
            catch (ArgumentNullException ex)
            {
                callback(null, ex);
            }

        }

正如您在上面所看到的,如果发生,我使用委托来传递异常 我的问题是,我怎样才能在Java 8中使用lambda。在Java 8中处理异常的最干净是什么。

2 个答案:

答案 0 :(得分:1)

您可以在Java中以类似的方式执行此操作。您需要一个带有两个参数的功能接口,例如java.util.function.BiConsumer。它看起来像这样:

public void queryIpRanges(BiConsumer<ObservableCollection<LocationRange>, Exception> callback) {
    try {
        // ...

        callback.accept(new ObservableCollection<LocationRange>(ranges), null);
    }
    catch (FormatException ex) {
        callback.accept(null, ex);
    }
    catch (ArgumentNullException ex) {
        callback.accept(null, ex);
    }
}

答案 1 :(得分:1)

做这样的事情:

public class Program {
    public static void main(String[] args) {
        final int[] myInt = new int[1];
        tryParseInt("123", (rs, ex) -> {
            if (ex == null) {
                myInt[0] = rs;
            } else {
                ex.printStackTrace();
                System.exit(1);
            }
        });
        System.out.println("myInt = " + myInt[0]);
    }

    static void tryParseInt(String text, Callback<Integer, NumberFormatException> callback) {
        try {
            callback.publish(Integer.parseInt(text), null);
        } catch (NumberFormatException ex) {
            callback.publish(null, ex);
        }
    }
}

@FunctionalInterface
interface Callback<T, E extends Exception> {
    void publish(T result, E ex);
}