Search code examples
javaexceptiontry-catchindexoutofboundsexception

Can we use "catch" to handle OutOfBoundsException with specific value?


I'm learning about exceptions in java. I have come across the following problem:

String bigstring = myscanner.nextLine();
String[] splited = bigstring.split("\\s+");
try {
    smallstring1 = splited[0];
    smallstring2 = splited[1];
    smallstring3 = splited[2];
} catch(java.lang.ArrayIndexOutOfBoundsException exc) {
    smallstring3 = null;
}

This would work if the user wants to type 2 words only.

What if he wants to type one word?

Can we somehow specify a value which we get in error after the colon?

Like:

java.lang.ArrayIndexOutOfBoundsException: 2

or

java.lang.ArrayIndexOutOfBoundsException: 1

Can we somehow use (for this example) this "2" or "1" in try/catch block?


Solution

  • You probably shouldn't use exceptions for normal program flow. Exceptions should usually be "exceptional".

    Anyway, although you cannot do that, you can use if statements inside your catch block. You can also check splited.length to check how big the array is.