blob: 7f6d0c5956ffdc81ee2352029eb6a7589b3a614c [file] [log] [blame]
jeffhao5d1ac922011-09-29 17:41:15 -07001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Andreas Gampebfdcdc12015-04-22 18:10:36 -070017// An exception that doesn't have a <init>(String) method.
18class BadError extends Error {
19 public BadError() {
20 super("This is bad by convention");
21 }
22}
23
24// A class that throws BadException during static initialization.
25class BadInit {
26 static int dummy;
27 static {
28 System.out.println("Static Init");
29 if (true) {
30 throw new BadError();
31 }
32 }
33}
34
jeffhao5d1ac922011-09-29 17:41:15 -070035/**
36 * Exceptions across method calls
37 */
38public class Main {
buzbee32412962012-06-26 16:27:56 -070039 public static void exceptions_007() {
jeffhao5d1ac922011-09-29 17:41:15 -070040 try {
41 catchAndRethrow();
42 } catch (NullPointerException npe) {
43 System.out.print("Got an NPE: ");
44 System.out.println(npe.getMessage());
45 npe.printStackTrace();
46 }
47 }
buzbee32412962012-06-26 16:27:56 -070048 public static void main (String args[]) {
49 exceptions_007();
Andreas Gampebfdcdc12015-04-22 18:10:36 -070050 exceptionsRethrowClassInitFailure();
buzbee32412962012-06-26 16:27:56 -070051 }
jeffhao5d1ac922011-09-29 17:41:15 -070052
53 private static void catchAndRethrow() {
54 try {
55 throwNullPointerException();
56 } catch (NullPointerException npe) {
57 NullPointerException npe2;
58 npe2 = new NullPointerException("second throw");
59 npe2.initCause(npe);
60 throw npe2;
61 }
62 }
63
64 private static void throwNullPointerException() {
65 throw new NullPointerException("first throw");
66 }
Andreas Gampebfdcdc12015-04-22 18:10:36 -070067
68 private static void exceptionsRethrowClassInitFailure() {
69 try {
70 try {
71 BadInit.dummy = 1;
72 throw new IllegalStateException("Should not reach here.");
73 } catch (BadError e) {
74 System.out.println(e);
75 }
76
77 // Check if it works a second time.
78
79 try {
80 BadInit.dummy = 1;
81 throw new IllegalStateException("Should not reach here.");
82 } catch (BadError e) {
83 System.out.println(e);
84 }
85 } catch (Exception error) {
86 error.printStackTrace();
87 }
88 }
jeffhao5d1ac922011-09-29 17:41:15 -070089}