开发者

Exception with multiple parameters in the constructor

开发者 https://www.devze.com 2023-04-11 19:23 出处:网络
I would like to know if it is fine to create an exception with multiple parameters in one constructor (different to throwable, string) or if this practice is bad?

I would like to know if it is fine to create an exception with multiple parameters in one constructor (different to throwable, string) or if this practice is bad?

Why do I need an exception with multiple parameters, well, let's suppose I am analyzing a matrix, and when there is an error, I will raise an exception with the position. I would like to give a clear error message in the exception, and also I would like to us开发者_运维知识库e internationalization, that means, messages in different languages.

For example, the messages could be:

There is an error in the position 4, 5.

Hubo un problema en la fila 4 con columna 5.

As you can see, the text is different for both messages, and the values are important for the message in order to be descriptive.

My approach is something like this:

public class MatrixException extends Exception {
  int x;
  int y;
  public MatrixException (int x, int y){
    this.x = x;
    this.y = y;
 }
 public String getMessage(){
   return Messages.getString("MatrixException.Message1") + this.x
       Messages.getString("MatrixException.Message2") + this.y
       Messages.getString("MatrixException.Message3");
 }
}

(The Messages class implements the ResourceBundle class)

With this kind of exception, I could create a descriptive message in the corresponding language, however I have never seen Exceptions with parameters different to String and Throwable.

I have tried to find information about how to write a well-defined exception hierarchy, but there is not a lot of documentation, and nothing about the constructors.

What do you think about my approach?


There's nothing wrong with this approach.

In fact, there are a few exception classes in the standard library with constructors that take arguments different to String and Throwable.

The first example that comes to mind is SQLException(String, String, int). Then there's URISyntaxException(String, String, int) and even EnumConstantNotPresentException(Class<? extends Enum>, String).


I like it. Your other option would be to format the string and use the normal Exception constructor, but I think what you have is fine.


Sure. If have additional parameters / fields in your custom exception class will make it easier to assess an issue if the exception is thrown, add away.


U can override method toString instead of method getmessage.

0

精彩评论

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

关注公众号