Multiple choice technology programming languages

From the following code fragments select the most appropriate way of throwing exceptions ?Assume that variable i is properly defined , in scope and has appropriate value

  1. if ( i > 10) { throws new IndexOutOfBoundsException("Index is out of bound!"); }

  2. if ( i > 10) { throw new IndexOutOfBoundsException("The value of index i=" + " is out of bound!" ); }

  3. if ( i > 10) { throw "Index is out of bound!"; }

  4. None of the ABove

Reveal answer Fill a bubble to check yourself
B Correct answer
Explanation

Java exceptions are objects thrown using the 'throw' keyword with 'new' to instantiate the exception class. Option B shows correct syntax: 'throw new IndexOutOfBoundsException(...)' creates the exception object and throws it. Option A uses 'throws' (a declaration keyword, not for throwing) and has a typo. Option C tries to throw a string literal directly, which isn't valid - only Throwable objects can be thrown.