The whole body of a try block executes, then, at the end of the try block, Java checks whether an exception happened, and executes the corresponding catch block if needed.


Exceptions get thrown at the end of the try block


Here is what's right.

Wherever an exception happens, execution stops immediately (it does not first continue until the end of a try block), and Java looks for a catch block to handle that exception.

Here is an example:

public void swapElement(int[] a, int[] b, int i) {
  try {
    int temp = a[i];
    a[i] = b[i];
    b[i] = temp;
  } catch (ArrayIndexOutOfBoundsException ex) {
    System.err.println("Index i out of bounds of one of the given arrays");

In the above code, if i>=a.length, the line int temp = a[i] throws an exception and the next two lines do not execute: control skips from a[i] (which throws an ArrayIndexOutOfBoundsException) directly to the catch block that catches the ArrayIndexOutOfBoundsException).

Stay up-to-date

Follow us on  twitter to hear about new misconceptions.