Search code examples
javaconstructorsuper

Extends Runtimeexception String message with different values


I want to create my own Exception which extends Runtimeexception. I the constructor I want it to print out different Strings, depending on the first parameter. The parameter is an integer and if its for example over 4 it should say "over" and under it should say "under". But I cannot do it with if and else because super has to be the first argument. Can anyone help?


Solution

  • You can call static methods in the constructor and pass their return value to the super class constructor:

    public class MyException extends RuntimeException {
        
        MyException(int v){
            super(chooseMessage(v));
        }
        private static String chooseMessage(int v){
            return v > 4 ? "over" : v < 4 ? "under" : "4";
        }
    }
    

    You also might be able to just use some ternary operators if your choice logic is simple enough:

        MyException(int v){
            super(v > 4 ? "over" : v < 4 ? "under" : "4");
        }
    

    Another way is to store your messages in an array (which might be better if you have a distinct message for each number):

        private static final String[] MESSAGES = { "a", "b", "c", "under", "4", "over" };
        
        MyException(int v){
            super(MESSAGES[v]);
        }