When there is a try-catch statement, Java first executes the statements in the try block, and then always executes the statements in the catch blocks.


Catch blocks always get executed


Here is what's right.

A try-catch statement looks like a sequence of statements that is partitioned into two subsequences (the one in the try block, followed by the one in the catch block):

int moveTo(final Position p) {
	moved = true;
	try {
		x = p.x;
		y = p.y;
	} catch (final NullPointerException ex) {
		x = 5;
		y = 8;
	return ++steps;

Java executes the statements in the try block up until an exception is thrown. At that point, execution stops immediately (this may be somewhere in the middle of the try block), and continues at the catch block that matches the thrown exception.

However, if no exception is thrown in the try block, then none of the catch blocks gets executed. The statements in the catch blocks are only executed to handle exceptions. They do not execute in the normal situation where no exceptions are thrown.

Stay up-to-date

Follow us on  twitter to hear about new misconceptions.