25

我在变量中有一个异常(未抛出)。

最好的选择是什么?

Exception exception = someObj.getExcp();
try {
    throw exception;
} catch (ExceptionExample1 e) {
    e.getSomeCustomViolations();
} catch (ExceptionExample2 e) {
    e.getSomeOtherCustomViolations(); 
}

或者

Exception exception = someObj.getExcp();
if (exception instanceof ExceptionExample1) {
    exception.getSomeCustomViolations();
} else if (exception instanceof ExceptionExample2) {
    exception.getSomeOtherCustomViolations();
}
4

4 回答 4

13

我建议使用instanceof它,因为它可能会更快。抛出异常是一项复杂且昂贵的操作。JVM 被优化为在发生异常的情况下速度很快。例外应该是例外。

请注意,该throw技术可能不会如图所示编译,如果您的异常类型是已检查异常,编译器将抱怨您必须捕获该类型或将其声明为已抛出(else { ... }如果您使用该技术,则对应于子句instanceof),这可能或者可能没有帮助,具体取决于您希望如何处理不属于特定子类型之一的异常。

于 2013-12-06T19:09:46.503 回答
12

讨厌破每个人的泡沫,但使用try/catch起来更快。这并不是说这是“正确”的方式,但如果性能是关键,那么这就是赢家。以下是以下程序的结果:

运行 1

  • 子运行 1:Instanceof:130 毫秒
  • 子运行 1:尝试/捕获:118 毫秒
  • 子运行 2:Instanceof:96 毫秒
  • 子运行 2:尝试/捕获:93 毫秒
  • 子运行 3:Instanceof:100 毫秒
  • 子运行 3:尝试/捕获:99 毫秒

运行 2

  • 子运行 1:Instanceof:140 毫秒
  • 子运行 1:尝试/捕获:111 毫秒
  • 子运行 2:Instanceof:92 毫秒
  • 子运行 2:尝试/捕获:92 毫秒
  • 子运行 3:Instanceof:105 毫秒
  • 子运行 3:尝试/捕获:95 毫秒

运行 3

  • 子运行 1:Instanceof:140 毫秒
  • 子运行 1:尝试/捕获:135 毫秒
  • 子运行 2:Instanceof:107 毫秒
  • 子运行 2:尝试/捕获:88 毫秒
  • 子运行 3:Instanceof:96 毫秒
  • 子运行 3:尝试/捕获:90 毫秒

测试环境

  • 爪哇:1.7.0_45
  • Mac OSX 小牛队

扣除每次运行的预热子运行,该instanceof方法最多只能达到try/catch. 该方法的平均(折扣热身)instanceof为 98 毫秒,平均try/catch为 92 毫秒。

请注意,我没有改变每种方法的测试顺序。我总是先测试一块instanceof然后再测试一块try/catch。我希望看到其他结果与这些发现相矛盾或证实。

public class test {

    public static void main (String [] args) throws Exception {
        long start = 0L;
        int who_cares = 0; // Used to prevent compiler optimization
        int tests = 100000;

        for ( int i = 0; i < 3; ++i ) {
            System.out.println("Testing instanceof");
            start = System.currentTimeMillis();
            testInstanceOf(who_cares, tests);
            System.out.println("instanceof completed in "+(System.currentTimeMillis()-start)+" ms "+who_cares);

            System.out.println("Testing try/catch");
            start = System.currentTimeMillis();
            testTryCatch(who_cares, tests);
            System.out.println("try/catch completed in "+(System.currentTimeMillis()-start)+" ms"+who_cares);
        }
    }

    private static int testInstanceOf(int who_cares, int tests) {
        for ( int i = 0; i < tests; ++i ) {
            Exception ex = (new Tester()).getException();
            if ( ex instanceof Ex1 ) {
                who_cares = 1;
            } else if ( ex instanceof Ex2 ) {
                who_cares = 2;
            }
        }
        return who_cares;
    }

    private static int testTryCatch(int who_cares, int tests) {
        for ( int i = 0; i < tests; ++i ) {
            Exception ex = (new Tester()).getException();
            try {
                throw ex;
            } catch ( Ex1 ex1 ) {
                who_cares = 1;
            } catch ( Ex2 ex2 ) {
                who_cares = 2;
            } catch ( Exception e ) {}
        }
        return who_cares;
    }

    private static class Ex1 extends Exception {}

    private static class Ex2 extends Exception {}

    private static java.util.Random rand = new java.util.Random();

    private static class Tester {
        private Exception ex;
        public Tester() {
            if ( rand.nextBoolean() ) {
                ex = new Ex1();
            } else {
                ex = new Ex2();
            }
        }
        public Exception getException() {
            return ex;
        }
    }
}
于 2013-12-06T20:35:53.900 回答
4

我强烈敦促您实际使用普通对象来表示您的“约束”。标记界面(例如Message)还是 ajava.lang.String取决于您。异常并不意味着按您的意愿使用,即使其中任何一个都可以工作(我希望第二个更快,但过早的优化......)。

于 2013-12-06T19:11:50.850 回答
3

您还可以通过为包含 getCustomViolation() 方法的自定义异常创建一个接口来使用多态性。然后每个自定义异常都将实现该接口和该方法。

于 2013-12-06T19:10:36.903 回答