简体   繁体   English

抛出异常并将其捕获到其他地方

[英]Throwing exceptions and catching them elsewhere

I was wondering if it was possible to write a method to throw an exception and have another method catch these exceptions. 我想知道是否有可能编写一个方法来引发异常并让另一个方法捕获这些异常。

For example, 例如,

public static void checkCircle() {
    try {
        checkPixel(a);
        checkPixel(b);
        checkPixel(c);
    } catch (MyException e) {
        System.out.println("not circle");
    } 

    private static void checkPixel(anything) {
        if (img.getRGB(xValue, yValue) != pOrigColour) {
            throw new MyException();
        }
    }

    class MyException extends Exception {
        public MyException() {
        }

        public MyException(String msg) {
            super(msg);
        }
    }

Thing is I want to the checkPixel method to throw a MyException , indicating that there is no circle, regardless of the results of the other calls. 我想让checkPixel方法抛出MyException ,表明没有圆,无论其他调用的结果如何。

Yes, it is possible. 对的,这是可能的。 In your method declaration, you can add a throws clause, which indicates that your method might throw an exception. 在方法声明中,可以添加throws子句,该子句指示您的方法可能会引发异常。

In your case, you should modify your method declaration like this: 在您的情况下,您应该像这样修改方法声明:

private static void checkPixel(anything) throws MyException {
    // ...
}

You should note that exceptions should be used for... exceptional situations. 您应注意,例外情况应用于...例外情况。 Using them for simple error handling is highly unconventional, and adds unnecessary burden on users of your classes. 使用它们进行简单的错误处理是非常常规的,并且给类的用户增加了不必要的负担。 In your case, you might want to add a boolean hasCircleAtLocation () method that would return true if there is a circle at the provided location. 在您的情况下,您可能想添加一个boolean hasCircleAtLocation ()方法,如果提供的位置处有一个圆,则该方法将返回true

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

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