Exception with multiple parameters in the constructor

12,548

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).

Share:
12,548
AngocA
Author by

AngocA

MBA &amp; MSc. IBM Champion 2015-2021. Look at my home page for more details: https://www.linkedin.com/in/angoca/, follow me at Twitter or GitHub. If you are interested in DB2 scripts please take a look at my repositories: log4db2: DB2 logger written in SQL PL - https://github.com/angoca/log4db2 db2unit: Unit testing framework for DB2 - https://github.com/angoca/db2unit db2-jnrpe: A set of plugins written in Java to monitor DB2 database via Nagios. https://github.com/angoca/db2-jnrpe DB2 monitoring scripts for Nagios - https://github.com/angoca/monitor-db2-with-nagios

Updated on June 12, 2022

Comments

  • AngocA
    AngocA almost 2 years

    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 use 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?