The problem in understanding how try-catch-finally blocks work

Please correct me if I am wrong, but I believe that the statements in the block try

are executed first, and then if any exception occurs finally

, the statements in the block catch

are executed and then the statements in the block are executed. If no exception is thrown, then the statements in the finally block are executed after the statements in the block have been executed, try

and the statements in the catch block are skipped.

Unless my concept is wrong, I don't understand why this piece of code is not working:

// sock is an object of the class Socket
public void run() {
    try {
        in = sock.getInputStream();
        scan = new Scanner(in);
        out = sock.getOutputStream();
        pw = new PrintWriter(out);
    } catch (IOException e) {
    } finally {


He still says that I need to surround the statement in a block finally




source to share

3 answers

Not! the instructions in the block are executed first try

. Then, if any exceptions occur, the block statements are executed catch

. And the block finally

is executed last. The block finally

is executed even if try

an exception is thrown in the block . In other words, if no exception occurs, the block is executed first try

and then the block is executed finally




In general, if your block catch

can catch



block try


try -> finally (If No Exception)
try -> catch -> finally (If Exception)




The statements in the block catch

are executed whenever an exception is encountered (which can be caught by the listed catch blocks). Statements in a block finally

will always be executed regardless of whether an exception was thrown in the block try


Your statement sock.close();

can potentially throw IOException

, so either you must have another try-catch block that wraps the inner try-catch, or it adds a declaration throws

to your run () method (and the calling method can have a try-catch block surrounding the call).

EDIT (as per comment): Statements inside catch

are executed first, then instructions in finally




All Articles