Throw and catch an exception, or use instanceof?
我在一个变量中有一个异常(没有抛出)。
最好的选择是什么?
1 2 3 4 5 6 7 8 | Exception exception = someObj.getExcp(); try { throw exception; } catch (ExceptionExample1 e) { e.getSomeCustomViolations(); } catch (ExceptionExample2 e) { e.getSomeOtherCustomViolations(); } |
或
1 2 3 4 5 6 | Exception exception = someObj.getExcp(); if (exception instanceof ExceptionExample1) { exception.getSomeCustomViolations(); } else if (exception instanceof ExceptionExample2) { exception.getSomeOtherCustomViolations(); } |
我建议使用
注意,
讨厌打破每个人的泡沫,但使用
跑1
- 子运行1:实例:130 ms
- 次运行1:尝试/捕获:118 ms
- 子运行2:实例:96 ms
- 子运行2:尝试/捕获:93 ms
- 子运行3:实例:100 ms
- 子运行3:尝试/捕获:99毫秒
跑2
- 子运行1:实例:140 ms
- 子运行1:尝试/捕获:111 ms
- 子运行2:实例:92 ms
- 次运行2:尝试/捕获:92 ms
- 子运行3:实例:105 ms
- 次运行3:尝试/捕获:95毫秒
跑3
- 子运行1:实例:140 ms
- 子运行1:尝试/捕获:135 ms
- 子运行2:实例:107 ms
- 子运行2:尝试/捕获:88毫秒
- 子运行3:实例:96 ms
- 次运行3:尝试/捕获:90 ms
测试环境
- Java:1.7.0Y45
- 麦克奥斯克斯小牛队
每一个运行的预热子运行的折扣,
请注意,我没有改变每种方法的测试顺序。我总是先测试一块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | 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; } } } |
我强烈建议您实际使用一个简单的对象来表示您的"约束"。标记接口(如
还可以通过为包含getCustomViolation()方法的自定义异常创建接口来使用多态性。然后,每个自定义异常都将实现该接口和该方法。