View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.juneau.commons.reflect;
18  
19  import static org.apache.juneau.commons.utils.Utils.*;
20  
21  import java.lang.reflect.*;
22  import java.text.*;
23  
24  /**
25   * General exception that occurs when trying to execute a constructor, method, or field using reflection.
26   *
27   *
28   * @serial exclude
29   */
30  public class ExecutableException extends RuntimeException {
31  
32  	private static final long serialVersionUID = 1L;
33  
34  	/**
35  	 * Constructor.
36  	 *
37  	 * @param message The {@link MessageFormat}-style message.
38  	 * @param args Optional {@link MessageFormat}-style arguments.
39  	 */
40  	public ExecutableException(String message, Object...args) {
41  		super(f(message, args));
42  	}
43  
44  	/**
45  	 * Constructor.
46  	 *
47  	 * @param causedBy The cause of this exception.
48  	 */
49  	public ExecutableException(Throwable causedBy) {
50  		super(causedBy);
51  	}
52  
53  	/**
54  	 * Constructor.
55  	 *
56  	 * @param causedBy The cause of this exception.
57  	 * @param message The {@link MessageFormat}-style message.
58  	 * @param args Optional {@link MessageFormat}-style arguments.
59  	 */
60  	public ExecutableException(Throwable causedBy, String message, Object...args) {
61  		super(f(message, args), causedBy);
62  	}
63  
64  	/**
65  	 * If the thrown exception was an {@link InvocationTargetException} returns the target exception.
66  	 * Otherwise returns the inner exception which is typically {@link IllegalArgumentException} or {@link IllegalAccessException}.
67  	 *
68  	 * @return The inner throwable.
69  	 */
70  	public Throwable getTargetException() {
71  		Throwable c = this.getCause();
72  		return c instanceof InvocationTargetException c2 ? c2.getTargetException() : c;
73  	}
74  
75  	/**
76  	 * Returns the caused-by exception if there is one.
77  	 *
78  	 * @return The caused-by exception if there is one, or this exception if there isn't.
79  	 */
80  	public Throwable unwrap() {
81  		Throwable t = getCause();
82  		return t == null ? this : t;
83  	}
84  }