Evgeniy Mishustin
Evgeniy Mishustin

Reputation: 3794

Call for asynchronous method in try-catch-finally block

I want to understand the following, suppose I have following block of code:

try{
    // do something
    asynchronousMethodCallThatWritesFileOutputStreamToSocket(fileOutputStream);
}catch (SomeException e){
    //handle exception
}finally{
    closeFileOutputStream(fileOutputStream);
}

My question is will the finally block close stream before asynchronous method finishes? Or will it somehow await? Please, any quotes from the books, if you know. Thank you very much.

N.B. This is pseudo-code, I know try-with-resources patterns.

Upvotes: 3

Views: 3712

Answers (1)

morels
morels

Reputation: 2105

The program is exited always with an uncaught exception because the async function is not try-catched correctly.

Basing on Java Asynchronous Exceptions: Can I catch them?

The only problem is that they (exceptions, ndr) may occur at any place in your program, so catching them reliably is hard. You would basically have to wrap the run method of all threads and the main method in a try..catch block, but you can't do that for threads you don't control (like the Swing EDT, or threads for timers etc.).

Upvotes: 4

Related Questions