1 /* 2 * @test /nodynamiccopyright/ 3 * @bug 4209652 4363318 4 * @summary Basic test for chained exceptions & Exception.getStackTrace(). 5 * @author Josh Bloch 6 */ 7 8 public class ChainedExceptions { 9 public static void main(String args[]) { 10 try { 11 a(); 12 } catch(HighLevelException e) { 13 StackTraceElement[] highTrace = e.getStackTrace(); 14 int depthTrim = highTrace.length - 2; 15 16 check(highTrace[0], "a", 48); 17 check(highTrace[1], "main", 11); 18 19 Throwable mid = e.getCause(); 20 StackTraceElement[] midTrace = mid.getStackTrace(); 21 if (midTrace.length - depthTrim != 4) 22 throw new RuntimeException("Mid depth"); 23 check(midTrace[0], "c", 58); 24 check(midTrace[1], "b", 52); 25 check(midTrace[2], "a", 46); 26 check(midTrace[3], "main", 11); 27 28 Throwable low = mid.getCause(); 29 StackTraceElement[] lowTrace = low.getStackTrace(); 30 if (lowTrace.length - depthTrim != 6) 31 throw new RuntimeException("Low depth"); 32 check(lowTrace[0], "e", 65); 33 check(lowTrace[1], "d", 62); 34 check(lowTrace[2], "c", 56); 35 check(lowTrace[3], "b", 52); 36 check(lowTrace[4], "a", 46); 37 check(lowTrace[5], "main", 11); 38 39 if (low.getCause() != null) 40 throw new RuntimeException("Low cause != null"); 41 } 42 } 43 44 static void a() throws HighLevelException { 45 try { 46 b(); 47 } catch(MidLevelException e) { 48 throw new HighLevelException(e); 49 } 50 } 51 static void b() throws MidLevelException { 52 c(); 53 } 54 static void c() throws MidLevelException { 55 try { 56 d(); 57 } catch(LowLevelException e) { 58 throw new MidLevelException(e); 59 } 60 } 61 static void d() throws LowLevelException { 62 e(); 63 } 64 static void e() throws LowLevelException { 65 throw new LowLevelException(); 66 } 67 68 private static final String OUR_CLASS = ChainedExceptions.class.getName(); 69 private static final String OUR_FILE_NAME = "ChainedExceptions.java"; 70 71 private static void check(StackTraceElement e, String methodName, int n) { 72 if (!e.getClassName().equals(OUR_CLASS)) 73 throw new RuntimeException("Class: " + e); 74 if (!e.getMethodName().equals(methodName)) 75 throw new RuntimeException("Method name: " + e); 76 if (!e.getFileName().equals(OUR_FILE_NAME)) 77 throw new RuntimeException("File name: " + e); 78 if (e.getLineNumber() != n) 79 throw new RuntimeException("Line number: " + e); 80 } 81 } 82 83 class HighLevelException extends Exception { 84 HighLevelException(Throwable cause) { super(cause); } 85 } 86 87 class MidLevelException extends Exception { 88 MidLevelException(Throwable cause) { super(cause); } 89 } 90 91 class LowLevelException extends Exception { 92 }