This does not provide a mechanism to do any cleaning up of system resources (e.g., closing open files) when an exception occurs. The solution is to add a block labelled finally, as follows.
try{ ... // Code that might generate error ... } catch (ExceptionType1 e1){...} // Corrective code for ExceptionType1 catch (ExceptionType2 e2){...} // Corrective code for ExceptionType2 finally{ ... // Always executed, whether try terminates normally or ... // exceptionally. Use for cleanup statements }
The semantics of finally is that it is always invoked, whether or not try terminates normally. If the try block does not raise an exception, after the try block control passes to the finally block and then to the next statement. If an exception does occur, the finally block is executed after the appropriate catch block. If no catch block applies, the finally block is executed before aborting the function and propagating the error back to the caller.