xref: /aosp_15_r20/external/jspecify/samples/Catch.java (revision 2167191df2fa07300797f1ac5b707370b5f38c48)
1 /*
2  * Copyright 2020 The JSpecify Authors.
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 import org.jspecify.annotations.NullMarked;
17 
18 @NullMarked
19 abstract class Catch {
x()20   void x() {
21     try {
22       throw new Exception();
23     } catch (Exception e) {
24       e.printStackTrace();
25       // TODO(cpovirk): Edit README to permit referencing java.lang.Exception. Or remove this.
26     }
27 
28     try {
29       doWork();
30     } catch (SomeError | SomeRuntimeException e) {
31     } catch (Throwable e) {
32       e.printStackTrace();
33     }
34 
35     try {
36       throw new RuntimeException();
37     } catch (RuntimeException | Error e) {
38       handleException(e);
39     }
40   }
41 
handleException(Throwable t)42   abstract void handleException(Throwable t);
43 
doWork()44   abstract void doWork() throws SomeException;
45 
46   static class SomeException extends Exception {}
47 
48   static class SomeRuntimeException extends RuntimeException {}
49 
50   static class SomeError extends Error {}
51 }
52