开发者

How to organize Exception classes without code duplication?

开发者 https://www.devze.com 2023-01-21 19:34 出处:网络
I have a number of custom Exception-inheriting classes in my package, which do not differ from their base class. The only purpose I have them is to distinguish one exception cause from the other, when

I have a number of custom Exception-inheriting classes in my package, which do not differ from their base class. The only purpose I have them is to distinguish one exception cause from the other, when it is thrown. This is how one of my Exception class looks like:

package com.XXX;
/**
 * Thrown when query format is invalid.
 */
public class InvalidFormatException extends Exception {
  /**
   * Public ctor.
   * @param m Supplementary message
   */
  public InvalidFormatException(final String m) {
    super(m);
  }
}

The problem is that all classes are absolutely identical, like twins. The only thing which is different is their names. I don't like this situation, since it's an obvious code duplication. In other la开发者_StackOverflow中文版nguages (like PHP, Python, etc.) I would declare these classes on-fly during runtime, but Java doesn't allow this, as well as I understand. Is there any workaround?


You may create a generic class with a code property settable with the controller. This way you can have only one class and instance when thrown.

That said, I don't agree when you say classes are twins. They represent totally different functional exception. Based on the separation of concerns pattern, the current implementation is the correct one. Using my generic class will mix concerns in your class and that should be forbidden.

Moreover, I see you inherit from Exception... I will not explains a lot but you should use RuntimeException for functional exceptions in your application. Look around on the web, there is a lot of literature about it.


The simple answer is "no", you cannot easily declare on the fly classes with Java. That noted, if you really wanted to do this, it is possible, you'll need to study how Java can compile classes at runtime. Another simplification is if all your exception classes are the same, excepting their names, you could define a base Exception class of your own that they extend.

Another thought, what value are you getting from having all these different Exception classes? Are you clients going to handle things differently depending on what Exception's thrown? If not, I'd suggest examining the Exception hierarchy you've created and simplifying.

Then, if you go that far, consider using RuntimeException as well. This might be grounds for a holy war, but if you really don't do anything special with what's thrown, there's not much value in forcing you client to deal with it. See Bruce Eckel's article on the subject for some perspective.

0

精彩评论

暂无评论...
验证码 换一张
取 消