If the return value of the API is invalid, I would like to use an exception that differs depending on the API.
A memorandum that it seems that it can be used like this in a situation where most of the processing is similar
ThrowExceptionTest.java
package reflection;
public class ThrowExceptionTest {
public static void main(String[] args) {
try {
throwException("w");
} catch (WwwwException e) {
System.out.println(e.getMessage());
} catch (ZzzzException e) {
System.out.println(e.getMessage());
}
}
/**
*Switch the exception thrown by the flag.
*
* @param flg
* @throws WwwwException
* @throws ZzzzException
*/
private static void throwException(String flg) throws WwwwException, ZzzzException {
WwwwException w = new WwwwException("w no good");
ZzzzException z = new ZzzzException("No with z");
if (ApiName.W.getText().equals(flg)) {
throw w;
}
if (ApiName.Z.getText().equals(flg)) {
throw z;
}
}
}
class WwwwException extends Exception {
private static final long serialVersionUID = 1L;
WwwwException(String msg) {
super(msg);
}
}
class ZzzzException extends Exception {
private static final long serialVersionUID = 1L;
ZzzzException(String msg) {
super(msg);
}
}
enum ApiName {
W("w"),
Z("z");
private String text;
private ApiName(final String text) {
this.text = text;
}
public String getText() {
return text;
}
}
Bad point: It's annoying to have a key Enum
Actually, I wanted to handle it with the Exception class as an argument.
Arguments: Class <? extends Throwable>
Processing: throw argument .newInstance ()
Like
But this is because I have to use reflection
Recommended Posts