views:

132

answers:

4

I am asking because if it is not, it can be abused as synchronizations mechanism. I am asking about Java.

+1  A: 

No, it's synchronous.

Try stepping through your code with a debugger, you'll see that it executes line after line, and will not continue if you break inside the catch.

Snake
+6  A: 

I'm not sure what you mean by "can be abused as synchronizations mechanism" - that doesn't make sense.

Exceptions are per thread - when an exception is thrown, the current thread's execution jumps to the place where the exception is caught. If it's not caught at all, the thread dies. Other threads are not affected.

Michael Borgwardt
I wanted to implement e.g. consumer-producer by throwing and exception, which if synchronized can be used as an event handled in catch block.
Gabriel Ščerbák
@Gabriel: no, it can't (unless I completely misunderstand you). An exception will always be caught by the same thread that throws it.
Michael Borgwardt
+5  A: 

JLS 11.3.2 Handling Asynchronous Exceptions

Most exceptions occur synchronously as a result of an action by the thread in which they occur, and at a point in the program that is specified to possibly result in such an exception. An asynchronous exception is, by contrast, an exception that can potentially occur at any point in the execution of a program.

Proper understanding of the semantics of asynchronous exceptions is necessary if high-quality machine code is to be generated.

Asynchronous exceptions are rare. They occur only as a result of:

  • An invocation of the stop methods of class Thread or ThreadGroup
  • An internal error in the Java virtual machine

So no, while rare, not all Exception handling is synchronous.

polygenelubricants
A: 

Exceptions occur during the execution of a thread. It does not make sense to have an asynchronous catch because the thread has to handle the exception. It cannot proceed till the exception is caught and taken care of. If the exception is not caught or thrown, the thread does not know what it has to do and simple dies and the program may/may not misbehave.

A thread throwing an exception and then proceeding without waiting for the catch does not make sense.

To answer your question, no catching is not asynchronous for all practical purposes.

Vaishak Suresh