Search code examples
javaexceptionthrow

exceptions in java


I wrote a code which checks all kinds of conditions.

If it meets the condition it does what it is supposed to, otherwise I want it to throw an exception.

Is there any special syntax for that? Otherwise the compiler wants me to return any array, which I don't want to, due to the pre-condition.

Here is part of my code:

public static int [] code(int[]arr){
    if ((arr!=null)&&(chack4and5(arr))&&(arr[arr.length-1]!=4)&&(TwoFours(arr))){
        int k=0;
        for(int i = 0; i<=arr.length-1; i++){
            if (arr[i] == 4){
                int place= pos(arr,k);
                arr[place]=arr[i+1];
                arr[i+1]=5;
                k=k+3;  
            }
        }
        return arr;
    }
    else { 
        System.out.println("Please enter a legal array which matches the pre- conditions");
        }
}

}


Solution

  • The way to throw an exception is

    throw new IllegalArgumentException(
            "Please enter a legal array which matches the pre- conditions");
    

    IllegalArgumentException is a Java runtime exception suitable for the current situation, but of course you can choose another one, or create and use your own type too. The only restriction is that it must be a subclass of java.lang.Exception.

    I would rearrrange your code though to check the preconditions first, then proceed if everything's fine - I find this more readable:

    if (arr == null || !chack4and5(arr) || arr[arr.length-1] == 4 || !TwoFours(arr)) {
      throw new IllegalArgumentException(
            "Please enter a legal array which matches the pre- conditions");
    }
    int k=0;
    
    for(int i = 0; i<=arr.length-1; i++){
        if (arr[i] == 4){
            int place= pos(arr,k);
            arr[place]=arr[i+1];
            arr[i+1]=5;
            k=k+3;
        }
    }
    return arr;
    

    (In fact, I would even prefer extracting the precondition check into a separate method - but I leave this to you.)