Construction. Try-Catch-Finally

[comp1110-90]

Like if, while, and switch, try-catch-finally is a control flow construct, written as follows:

try { // a bunch of statements that form // the normal path of execution } catch(TypeOfException e) { // if any code inside the try-block // throws an object of type // TypeOfException, AND no nested // try-block inside the try-block // caught it, then we immediately // abort execution the code in the // try-block and instead continue // in here } catch(AnotherTypeOfException e) { // same as above, but for a // different class of exceptions } finally { // regardless of whether the // try-block finished normally // or threw an exception, and // in the second case, regardless // of whether that exception was // caught here or not, the code // in here will be executed before // we leave the overall construct }

You can generally have arbitrarily many catch-blocks after a try-block, and at most one finally-block. There must be at least one catch-block or a finally-block after a try-block.

bars magnifying-glass caret-down plus minus arrow-right xmark