TryCatchMandatory
DRAFT

Misconception:

If code can throw an exception, that code has to be inside a try/catch block. The exception can be propagated to the calling method by throwing it from the catch block, e.g., like this: try { c = a[i]; } catch (ArrayIndexOutOfBoundsException ex) { throw ex; }.

Incorrect

If code could throw an exception, you must surround that code with a try/catch block

Correct

Correction
Here is what's right.

You can surround the problematic code with a try/catch, but you do not have to. Specifically, if you want the exception to propagate to the caller, then you do not want to catch it. You just want to declare it (with throws in the method header).

public int m(int i) throws ArrayIndexOutOfBoundsException {
  return c = a[i];
}

Or, in this case, where the exception is an unchecked exception (e.g., a subtype of RuntimeException), the declaration is not needed:

public int m(int i) {
  return c = a[i];
}

The ArrayIndexOutOfBoundsException that could be thrown by the array indexing operator will be thrown to the caller of method m(), and if that caller does not catch it, it will be thrown to its caller, and so on. If nobody catches the exception, then the JVM will receive it, and it will print a stack trace.

Language

Java

Concepts

Stay up-to-date

Follow us on  twitter to hear about new misconceptions.