-8

I go over the all build-in exception in JDK, I only find SizeLimitExceededException when size exceed the expected length. However, if I want to throw an exception when size limit is below the expected length, there is no such built-in exception class that I can call?

Update:

SSN is 9 digits length. If input SSN is shorter than 9 digits length, then I want to throw this exception.

MWiesner
  • 8,868
  • 11
  • 36
  • 70
FullStackDeveloper
  • 910
  • 1
  • 16
  • 40
  • 1
    I'm not exactly sure about the reasoning behind throwing exceptions if something is _below_ a certain limit but you can always create your own class. – Marvin Dec 12 '19 at 22:09
  • 1
    No reason to not create your own exception class. – SephB Dec 12 '19 at 22:12
  • @Marvin I did not see any reason why JDK has out of box of 'SizeLimitExceededException', but not something like 'SizeLimitBelowException'. JDK should have it, instead of we create it by ourself. – FullStackDeveloper Dec 13 '19 at 02:01
  • What would be the point in having such an exception? The JDK should provide built-in classes for common and sensible use cases and for a `SizeLimitBelowException` I don't see either. Do you want to elaborate and clarify your case? – Marvin Dec 13 '19 at 09:43
  • @Marvin My question is simple, Why JDK have 'SizeLimitExceededException' now but not have something like 'SizeLimitBelowException'? – FullStackDeveloper Dec 13 '19 at 16:37
  • Have you considered `javax.naming.LimitExceededException`? By the way, you could report a bug and claim that a `SizeLimitBelowException` is required but does not exist. – Abra Dec 16 '19 at 02:58
  • Can you give us context to what are you doing and how? – Kumar Rohit Dec 16 '19 at 04:47
  • The `SizeLimitExceededException` and also `LimitExceededException` are from the `javax.naming` package which is quite special. You shouldn't use any of them just because the name sound right. Go for IndexOutOfBoundException (which is from `java.lang`) as @waifu_anton points out or use your own Exception. – Alexander Dec 16 '19 at 09:04
  • @KumarRohit SSN is 9 digits length. If input SSN is shorter than 9 digits length, then I want to throw that exception – FullStackDeveloper Dec 17 '19 at 05:04
  • Just throw an IllegalArgumentException for this with an appropriate message. It will be obvious to anyone looking at the logs what happened. – Old Nick Dec 19 '19 at 11:29

4 Answers4

7

While using a fitting exception is good practice and you should spend some time to look for a fitting one (as you did), there is usually also no need to go over board with it.

In your example, I'd consider it totally fine if you'd just throw an new IllegalArgumentException("SSN is only of length <X> but length 9 is required"). It will fail the execution and give you a meaningful stacktrace.

Be aware that it is considered bad practice to use exception for control flow. So please never ever use something like

try {
    person.setSSN(ssn);
catch (SSNTooShortException e) {
    println("SSN too short! Please try again");
}

Instead use a custom validator to check SSN before setting it and only use the exception to guard against programming error.

if (!SSNFormat.matches(ssn)) { // <-- whoops condition is inverted
    person.setSSN(ssn);
}

This snippet will hopefully fail soon in your (unit) test and you will know that your programming logic is flawed.

Of course, depending of your application, instead of using your custom validator, you could and should use one of the many validator frameworks (for an example, look at Hibernate's constraints, but virtually all big frameworks support validation in one or the other form).

Arvid Heise
  • 3,524
  • 5
  • 11
2

Suppose there was a built-in JDK SizeLimitSubceededException (I just learned that subceeded is the opposite of exceeded). Would your code, which checks the length of the SSN throw one exception - SizeLimitExceededException - if the size exceeds the expected size, and another exception - SizeLimitSubceededException - if the size subceeds the expected size?

This would be awkward:

  1. You would have to specify both exceptions in the throws clause of your method (assuming SizeLimitSubceededException would be a checked exception, same as SizeLimitExceededException).
  2. The caller of your method would have to handle both exceptions.

And what if the size is right, but something else is wrong - for example, the SNN contains non-digit characters? Would you throw a third exception for that?

My point is that you'd be better off throwing a single type of exception from the method that sets the SSN.

If you want this to be a checked exception (which I suggest, in order to force the caller to handle it), I suggest defining your own custom exception - perhaps InvalidSSNException. This exception can have a constructor with several arguments - one of them the invalid SSN, another could be a boolean that indicates if the exception was thrown due to incorrect length.

Then your custom exception can produce an error message that matches the reason to the failure:

  1. If the entered SSN had the wrong length (and it doesn't matter if it's too long or too short), the message would specify the expected length (9).

  2. If the entered SSN had the correct length, the message would specify the valid characters (digits only).

Example:

class Person {

    ...

    public setSSN (String ssn) throws InvalidSSNException
    {
        if (ssn == null) {
            throw new InvalidSSNException (ssn, false);
        }
        if (ssn.length() != 9) {
            // exception thrown as a result of invalid length
            throw new InvalidSSNException (ssn, true);
        }
        for (char c : ssn.toCharArray()) {
            if (c < '0' || c > '9') {
                // exception thrown as a result of invalid character
                throw new InvalidSSNException (ssn, false);
            }
        }
        this.ssn = ssn;
    }
    ...

}
Eran
  • 387,369
  • 54
  • 702
  • 768
1

Maybe you want something like IndexOutOfBoundsException. It is thrown to indicate that an index of some sort of data is out of range. https://docs.oracle.com/javase/7/docs/api/java/lang/IndexOutOfBoundsException.html

waifu_anton
  • 53
  • 2
  • 7
  • `IndexOutOfBoundsException` is not the best fit; it is thrown by the string itself when you would access the 9. character of the SSN string, but it is too short. – Arvid Heise Dec 17 '19 at 07:13
1

You can create an exception as

public class UnderBottomException extends Exception {
  public UnderBottomException(int dim, int param) {
      super();
      System.out.println("you entered a length of : " + dim + " whereas the minimum length expected is : " + param);
  }
}

This exception will be implementable this way in your POJO :

public class Register {
  private int[] registre;
  private int minRange = 9;

  public Register(int[] parametre) throws UnderBottomException {
    if (parametre.length < this.minRange) {
        throw new UnderBottomException(parametre.length, this.minRange);
    }
    else {  
        this.registre = new int[parametre.length];
        for (int i = 0 ; i < this.registre.length; i++)
            this.registre[i] = parametre[i];
    }
  }

  public int[] getRegistre() {
    return registre;
  }

  public int getMinRange() {
    return minRange;
  }
}

And finaly you use your object catching exception like this :

public class Main {
  public static void main(String[] args) {
    int[] a = {1,2,3,4,5,6,7,8};
    try {
        Register monRegistre = new Register(a);
        System.out.println("Nickel le sous registre de rang 2 = " + monRegistre.getRegistre()[1]);
    }
    catch(UnderBottomException e) {
    }
  }
}

Output : you entered a length of : 8 whereas the minimum length expected is : 9

kevin ternet
  • 4,514
  • 2
  • 19
  • 27