Exception switching method

Common processing that wants to switch exceptions depending on the thing

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

It didn't work for various reasons. By the way, it was possible with `NumberFormatException` I knew it was no good, so I stopped looking at what I could do. Probably not a system that gets caught in ʻIllegalArgumentException` or other exceptions Anyway
Well, it doesn't seem to be bad to make a lot of similar methods, only the exceptions to throw are different. If they are similar, I want to put them together.

Recommended Posts

Exception switching method
Method
exception
Java method
to_i method
java (method)
getRequestDispatcher () method
merge method
Map method
include method
Abstract method
initialize method
List method
puts method
Exception handling
Java method
Class method
save! method
Self-made Exception
getParameter method
[Java] method
private method
rails method
Exception handling Exception
[Java] method