Why do suspending functions throw exceptions in finally2019 Community Moderator ElectionDo all suspend functions have a Job?Kotlin suspend funWhen should I make my normal function suspending function?Aspect around Kotlin suspended function@Around aspect and Kotlin suspended functionSuspended function to read from InputStreamHow to continue a suspend function in a dynamic proxy in the same coroutine?How to delay within async function that returns Deferred<T>How to get current `coroutineContext` from a non-suspend function?How to struture coroutine code without suspend function
Where was Karl Mordo in Infinity War?
How can atoms be electrically neutral when there is a difference in the positions of the charges?
Is there a ternary operator in math
Whom do I have to contact for a ticket refund in case of denied boarding (in the EU)?
How do you say "powers of ten"?
What is knowledge and vision?
Second-rate spelling
How to deny access to SQL Server to certain login over SSMS, but allow over .Net SqlClient Data Provider
the need of reserving one's ability in job interviews
Tcolorbox as an item in list environment
chrony vs. systemd-timesyncd – What are the differences and use cases as NTP clients?
How can I be pwned if I'm not registered on that site?
Replacement ford fiesta radiator has extra hose
How to kill a localhost:8080
Rationale to prefer local variables over instance variables?
What are all the squawk codes?
What is better: yes / no radio, or simple checkbox?
What do the pedals on grand pianos do?
When was drinking water recognized as crucial in marathon running?
Is there a frame of reference in which I was born before I was conceived?
Is the set of paths between any two points moving only in units on the plane countable or uncountable?
What is the difference between throw e and throw new Exception(e)?
What am I? I am in theaters and computer programs
What type of postprocessing gives the effect of people standing out
Why do suspending functions throw exceptions in finally
2019 Community Moderator ElectionDo all suspend functions have a Job?Kotlin suspend funWhen should I make my normal function suspending function?Aspect around Kotlin suspended function@Around aspect and Kotlin suspended functionSuspended function to read from InputStreamHow to continue a suspend function in a dynamic proxy in the same coroutine?How to delay within async function that returns Deferred<T>How to get current `coroutineContext` from a non-suspend function?How to struture coroutine code without suspend function
As the title says, why do suspending functions throw exceptions in finally?
With regular functions, the finally-block executes all of them:
import kotlinx.coroutines.*
fun main()
val handler = CoroutineExceptionHandler _, exception ->
println("Caught $exception")
val job = GlobalScope.launch(handler)
launch
// the first child
try
println("inside try")
delay(1000)
finally
println("Children are cancelled, but exception is not handled until all children terminate")
Thread.sleep(1000)
println("thread.sleep executed")
//foo()
println("The first child finished its non cancellable block")
launch
// the second child
delay(10)
println("Second child throws an exception")
throw ArithmeticException()
Thread.sleep(1000000)
println("complete")
Here, for example, when I do Thread.sleep(1000) it prints:
"The first child finished its non cancellable block"
but if I change that line to delay(1000), it does not.
From my understanding, in a finally-block, the exception, if it exists, is thrown after executing the entire block.
But in this case, delay causes this exception to be thrown early.
On the other hand, Thread.sleep does not.
Can someone help explain?
kotlin kotlinx.coroutines kotlin-coroutines
add a comment |
As the title says, why do suspending functions throw exceptions in finally?
With regular functions, the finally-block executes all of them:
import kotlinx.coroutines.*
fun main()
val handler = CoroutineExceptionHandler _, exception ->
println("Caught $exception")
val job = GlobalScope.launch(handler)
launch
// the first child
try
println("inside try")
delay(1000)
finally
println("Children are cancelled, but exception is not handled until all children terminate")
Thread.sleep(1000)
println("thread.sleep executed")
//foo()
println("The first child finished its non cancellable block")
launch
// the second child
delay(10)
println("Second child throws an exception")
throw ArithmeticException()
Thread.sleep(1000000)
println("complete")
Here, for example, when I do Thread.sleep(1000) it prints:
"The first child finished its non cancellable block"
but if I change that line to delay(1000), it does not.
From my understanding, in a finally-block, the exception, if it exists, is thrown after executing the entire block.
But in this case, delay causes this exception to be thrown early.
On the other hand, Thread.sleep does not.
Can someone help explain?
kotlin kotlinx.coroutines kotlin-coroutines
1
share your code
– Radesh
2 days ago
add a comment |
As the title says, why do suspending functions throw exceptions in finally?
With regular functions, the finally-block executes all of them:
import kotlinx.coroutines.*
fun main()
val handler = CoroutineExceptionHandler _, exception ->
println("Caught $exception")
val job = GlobalScope.launch(handler)
launch
// the first child
try
println("inside try")
delay(1000)
finally
println("Children are cancelled, but exception is not handled until all children terminate")
Thread.sleep(1000)
println("thread.sleep executed")
//foo()
println("The first child finished its non cancellable block")
launch
// the second child
delay(10)
println("Second child throws an exception")
throw ArithmeticException()
Thread.sleep(1000000)
println("complete")
Here, for example, when I do Thread.sleep(1000) it prints:
"The first child finished its non cancellable block"
but if I change that line to delay(1000), it does not.
From my understanding, in a finally-block, the exception, if it exists, is thrown after executing the entire block.
But in this case, delay causes this exception to be thrown early.
On the other hand, Thread.sleep does not.
Can someone help explain?
kotlin kotlinx.coroutines kotlin-coroutines
As the title says, why do suspending functions throw exceptions in finally?
With regular functions, the finally-block executes all of them:
import kotlinx.coroutines.*
fun main()
val handler = CoroutineExceptionHandler _, exception ->
println("Caught $exception")
val job = GlobalScope.launch(handler)
launch
// the first child
try
println("inside try")
delay(1000)
finally
println("Children are cancelled, but exception is not handled until all children terminate")
Thread.sleep(1000)
println("thread.sleep executed")
//foo()
println("The first child finished its non cancellable block")
launch
// the second child
delay(10)
println("Second child throws an exception")
throw ArithmeticException()
Thread.sleep(1000000)
println("complete")
Here, for example, when I do Thread.sleep(1000) it prints:
"The first child finished its non cancellable block"
but if I change that line to delay(1000), it does not.
From my understanding, in a finally-block, the exception, if it exists, is thrown after executing the entire block.
But in this case, delay causes this exception to be thrown early.
On the other hand, Thread.sleep does not.
Can someone help explain?
kotlin kotlinx.coroutines kotlin-coroutines
kotlin kotlinx.coroutines kotlin-coroutines
edited 1 hour ago
Alex Yu
2,0361625
2,0361625
asked 2 days ago
Typical Highschooler Typical Highschooler
113
113
1
share your code
– Radesh
2 days ago
add a comment |
1
share your code
– Radesh
2 days ago
1
1
share your code
– Radesh
2 days ago
share your code
– Radesh
2 days ago
add a comment |
3 Answers
3
active
oldest
votes
Suspending functions in Kotlin work differently than blocking function.
When you cancel a Job, at the first suspension after the cancellation the execution will be stopped, even if you are in a finally block. If you use Thread.sleep(1000) instead of delay(1000) in your finally block, there are no suspensions taking place, because Thread.sleep() is blocking, not suspending, so your whole finally block gets executed.
Note that using blocking functions inside of suspending functions is an anti-pattern and should be avoided!!
To achieve this desired behavior without using blocking functions, use withContext(NonCancellable) ... as described here.
Your example code should look like this:
fun main()
val handler = CoroutineExceptionHandler _, exception ->
println("Caught $exception")
val job = GlobalScope.launch(handler)
launch
// the first child
try
println("inside try")
delay(1000000)
finally
withContext(NonCancellable)
println("Children are cancelled, but exception is not handled until all children terminate")
delay(1000) // This suspension cannot be cancelled
println("delay executed")
//foo()
println("The first child finished its non cancellable block")
launch
// the second child
delay(10)
println("Second child throws an exception")
throw ArithmeticException()
Thread.sleep(1000000)
println("complete")
The output:
inside try
Second child throws an exception
Children are cancelled, but exception is not handled until all children terminate
delay executed
The first child finished its non cancellable block
Caught java.lang.ArithmeticException
New contributor
functionaldude is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
Even though your question is unclear, I can say that finally is always executed, you are right, in doing so it tries to run a suspended function which by definition is locked until you call it back. By default, a suspend function for instance in Java, means execution is suspended. Finally block trying to execute without using resume() would throw an exception. Once, your function has been suspended, you need to use another proper function to revive function from executing. Credit goes to https://www.tutorialspoint.com/java/java_thread_control.htm for example of code.
1 public void suspend()
This method puts a thread in the suspended state and can be resumed using resume() method.
2 public void stop()
This method stops a thread completely.
3 public void resume()
This method resumes a thread, which was suspended using suspend() method.
4 public void wait()
Causes the current thread to wait until another thread invokes the notify().
5 public void notify()
Wakes up a single thread that is waiting on this object's monitor.
class RunnableDemo implements Runnable
public Thread t;
private String threadName;
boolean suspended = false;
RunnableDemo( String name)
threadName = name;
System.out.println("Creating " + threadName );
public void run()
System.out.println("Running " + threadName );
try
for(int i = 10; i > 0; i--)
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(300);
synchronized(this)
while(suspended)
wait();
catch (InterruptedException e)
System.out.println("Thread " + threadName + " interrupted.");
System.out.println("Thread " + threadName + " exiting.");
public void start ()
System.out.println("Starting " + threadName );
if (t == null)
t = new Thread (this, threadName);
t.start ();
void suspend()
suspended = true;
synchronized void resume()
suspended = false;
notify();
public class TestThread
public static void main(String args[])
RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();
RunnableDemo R2 = new RunnableDemo( "Thread-2");
R2.start();
try
Thread.sleep(1000);
R1.suspend();
System.out.println("Suspending First Thread");
Thread.sleep(1000);
R1.resume();
System.out.println("Resuming First Thread");
R2.suspend();
System.out.println("Suspending thread Two");
Thread.sleep(1000);
R2.resume();
System.out.println("Resuming thread Two");
catch (InterruptedException e)
System.out.println("Main thread Interrupted");
try
System.out.println("Waiting for threads to finish.");
R1.t.join();
R2.t.join();
catch (InterruptedException e)
System.out.println("Main thread Interrupted");
System.out.println("Main thread exiting.");
1
the original question is about Kotlin coroutines; this has nothing to do with Java's thread suspending
– P.J.Meisch
2 days ago
i presume concept would be same.
– surendrapanday
2 days ago
Suspending functions are vastly different from blocking functions!
– functionaldude
1 hour ago
add a comment |
From my understanding, in a
finally-block, the exception, if it exists, is thrown after executing the entire block.
This is not true. If a finally block throws an exception, it causes the finally block to terminate abruptly with that exception. Any exception that was thrown within try is thus discarded. This is exactly what happens in your case: the finally block of the first child coroutine receives a CancellationException on the delay(1000) line. Thread.sleep(1000) is a blocking, non-cancellable function, therefore it doesn't observe the cancellation.
You probably mixed up this with the fact that, if the try block throws an exception, then first the complete finally block is executed before throwing the exception. The finally block is required to complete normally in order for this to happen.
So I believe you aren't describing any difference in the behavior of plain and suspendable functions.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54965849%2fwhy-do-suspending-functions-throw-exceptions-in-finally%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
Suspending functions in Kotlin work differently than blocking function.
When you cancel a Job, at the first suspension after the cancellation the execution will be stopped, even if you are in a finally block. If you use Thread.sleep(1000) instead of delay(1000) in your finally block, there are no suspensions taking place, because Thread.sleep() is blocking, not suspending, so your whole finally block gets executed.
Note that using blocking functions inside of suspending functions is an anti-pattern and should be avoided!!
To achieve this desired behavior without using blocking functions, use withContext(NonCancellable) ... as described here.
Your example code should look like this:
fun main()
val handler = CoroutineExceptionHandler _, exception ->
println("Caught $exception")
val job = GlobalScope.launch(handler)
launch
// the first child
try
println("inside try")
delay(1000000)
finally
withContext(NonCancellable)
println("Children are cancelled, but exception is not handled until all children terminate")
delay(1000) // This suspension cannot be cancelled
println("delay executed")
//foo()
println("The first child finished its non cancellable block")
launch
// the second child
delay(10)
println("Second child throws an exception")
throw ArithmeticException()
Thread.sleep(1000000)
println("complete")
The output:
inside try
Second child throws an exception
Children are cancelled, but exception is not handled until all children terminate
delay executed
The first child finished its non cancellable block
Caught java.lang.ArithmeticException
New contributor
functionaldude is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
Suspending functions in Kotlin work differently than blocking function.
When you cancel a Job, at the first suspension after the cancellation the execution will be stopped, even if you are in a finally block. If you use Thread.sleep(1000) instead of delay(1000) in your finally block, there are no suspensions taking place, because Thread.sleep() is blocking, not suspending, so your whole finally block gets executed.
Note that using blocking functions inside of suspending functions is an anti-pattern and should be avoided!!
To achieve this desired behavior without using blocking functions, use withContext(NonCancellable) ... as described here.
Your example code should look like this:
fun main()
val handler = CoroutineExceptionHandler _, exception ->
println("Caught $exception")
val job = GlobalScope.launch(handler)
launch
// the first child
try
println("inside try")
delay(1000000)
finally
withContext(NonCancellable)
println("Children are cancelled, but exception is not handled until all children terminate")
delay(1000) // This suspension cannot be cancelled
println("delay executed")
//foo()
println("The first child finished its non cancellable block")
launch
// the second child
delay(10)
println("Second child throws an exception")
throw ArithmeticException()
Thread.sleep(1000000)
println("complete")
The output:
inside try
Second child throws an exception
Children are cancelled, but exception is not handled until all children terminate
delay executed
The first child finished its non cancellable block
Caught java.lang.ArithmeticException
New contributor
functionaldude is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
Suspending functions in Kotlin work differently than blocking function.
When you cancel a Job, at the first suspension after the cancellation the execution will be stopped, even if you are in a finally block. If you use Thread.sleep(1000) instead of delay(1000) in your finally block, there are no suspensions taking place, because Thread.sleep() is blocking, not suspending, so your whole finally block gets executed.
Note that using blocking functions inside of suspending functions is an anti-pattern and should be avoided!!
To achieve this desired behavior without using blocking functions, use withContext(NonCancellable) ... as described here.
Your example code should look like this:
fun main()
val handler = CoroutineExceptionHandler _, exception ->
println("Caught $exception")
val job = GlobalScope.launch(handler)
launch
// the first child
try
println("inside try")
delay(1000000)
finally
withContext(NonCancellable)
println("Children are cancelled, but exception is not handled until all children terminate")
delay(1000) // This suspension cannot be cancelled
println("delay executed")
//foo()
println("The first child finished its non cancellable block")
launch
// the second child
delay(10)
println("Second child throws an exception")
throw ArithmeticException()
Thread.sleep(1000000)
println("complete")
The output:
inside try
Second child throws an exception
Children are cancelled, but exception is not handled until all children terminate
delay executed
The first child finished its non cancellable block
Caught java.lang.ArithmeticException
New contributor
functionaldude is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Suspending functions in Kotlin work differently than blocking function.
When you cancel a Job, at the first suspension after the cancellation the execution will be stopped, even if you are in a finally block. If you use Thread.sleep(1000) instead of delay(1000) in your finally block, there are no suspensions taking place, because Thread.sleep() is blocking, not suspending, so your whole finally block gets executed.
Note that using blocking functions inside of suspending functions is an anti-pattern and should be avoided!!
To achieve this desired behavior without using blocking functions, use withContext(NonCancellable) ... as described here.
Your example code should look like this:
fun main()
val handler = CoroutineExceptionHandler _, exception ->
println("Caught $exception")
val job = GlobalScope.launch(handler)
launch
// the first child
try
println("inside try")
delay(1000000)
finally
withContext(NonCancellable)
println("Children are cancelled, but exception is not handled until all children terminate")
delay(1000) // This suspension cannot be cancelled
println("delay executed")
//foo()
println("The first child finished its non cancellable block")
launch
// the second child
delay(10)
println("Second child throws an exception")
throw ArithmeticException()
Thread.sleep(1000000)
println("complete")
The output:
inside try
Second child throws an exception
Children are cancelled, but exception is not handled until all children terminate
delay executed
The first child finished its non cancellable block
Caught java.lang.ArithmeticException
New contributor
functionaldude is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
edited 1 hour ago
New contributor
functionaldude is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
answered 1 hour ago
functionaldudefunctionaldude
707
707
New contributor
functionaldude is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
functionaldude is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
functionaldude is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
add a comment |
Even though your question is unclear, I can say that finally is always executed, you are right, in doing so it tries to run a suspended function which by definition is locked until you call it back. By default, a suspend function for instance in Java, means execution is suspended. Finally block trying to execute without using resume() would throw an exception. Once, your function has been suspended, you need to use another proper function to revive function from executing. Credit goes to https://www.tutorialspoint.com/java/java_thread_control.htm for example of code.
1 public void suspend()
This method puts a thread in the suspended state and can be resumed using resume() method.
2 public void stop()
This method stops a thread completely.
3 public void resume()
This method resumes a thread, which was suspended using suspend() method.
4 public void wait()
Causes the current thread to wait until another thread invokes the notify().
5 public void notify()
Wakes up a single thread that is waiting on this object's monitor.
class RunnableDemo implements Runnable
public Thread t;
private String threadName;
boolean suspended = false;
RunnableDemo( String name)
threadName = name;
System.out.println("Creating " + threadName );
public void run()
System.out.println("Running " + threadName );
try
for(int i = 10; i > 0; i--)
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(300);
synchronized(this)
while(suspended)
wait();
catch (InterruptedException e)
System.out.println("Thread " + threadName + " interrupted.");
System.out.println("Thread " + threadName + " exiting.");
public void start ()
System.out.println("Starting " + threadName );
if (t == null)
t = new Thread (this, threadName);
t.start ();
void suspend()
suspended = true;
synchronized void resume()
suspended = false;
notify();
public class TestThread
public static void main(String args[])
RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();
RunnableDemo R2 = new RunnableDemo( "Thread-2");
R2.start();
try
Thread.sleep(1000);
R1.suspend();
System.out.println("Suspending First Thread");
Thread.sleep(1000);
R1.resume();
System.out.println("Resuming First Thread");
R2.suspend();
System.out.println("Suspending thread Two");
Thread.sleep(1000);
R2.resume();
System.out.println("Resuming thread Two");
catch (InterruptedException e)
System.out.println("Main thread Interrupted");
try
System.out.println("Waiting for threads to finish.");
R1.t.join();
R2.t.join();
catch (InterruptedException e)
System.out.println("Main thread Interrupted");
System.out.println("Main thread exiting.");
1
the original question is about Kotlin coroutines; this has nothing to do with Java's thread suspending
– P.J.Meisch
2 days ago
i presume concept would be same.
– surendrapanday
2 days ago
Suspending functions are vastly different from blocking functions!
– functionaldude
1 hour ago
add a comment |
Even though your question is unclear, I can say that finally is always executed, you are right, in doing so it tries to run a suspended function which by definition is locked until you call it back. By default, a suspend function for instance in Java, means execution is suspended. Finally block trying to execute without using resume() would throw an exception. Once, your function has been suspended, you need to use another proper function to revive function from executing. Credit goes to https://www.tutorialspoint.com/java/java_thread_control.htm for example of code.
1 public void suspend()
This method puts a thread in the suspended state and can be resumed using resume() method.
2 public void stop()
This method stops a thread completely.
3 public void resume()
This method resumes a thread, which was suspended using suspend() method.
4 public void wait()
Causes the current thread to wait until another thread invokes the notify().
5 public void notify()
Wakes up a single thread that is waiting on this object's monitor.
class RunnableDemo implements Runnable
public Thread t;
private String threadName;
boolean suspended = false;
RunnableDemo( String name)
threadName = name;
System.out.println("Creating " + threadName );
public void run()
System.out.println("Running " + threadName );
try
for(int i = 10; i > 0; i--)
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(300);
synchronized(this)
while(suspended)
wait();
catch (InterruptedException e)
System.out.println("Thread " + threadName + " interrupted.");
System.out.println("Thread " + threadName + " exiting.");
public void start ()
System.out.println("Starting " + threadName );
if (t == null)
t = new Thread (this, threadName);
t.start ();
void suspend()
suspended = true;
synchronized void resume()
suspended = false;
notify();
public class TestThread
public static void main(String args[])
RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();
RunnableDemo R2 = new RunnableDemo( "Thread-2");
R2.start();
try
Thread.sleep(1000);
R1.suspend();
System.out.println("Suspending First Thread");
Thread.sleep(1000);
R1.resume();
System.out.println("Resuming First Thread");
R2.suspend();
System.out.println("Suspending thread Two");
Thread.sleep(1000);
R2.resume();
System.out.println("Resuming thread Two");
catch (InterruptedException e)
System.out.println("Main thread Interrupted");
try
System.out.println("Waiting for threads to finish.");
R1.t.join();
R2.t.join();
catch (InterruptedException e)
System.out.println("Main thread Interrupted");
System.out.println("Main thread exiting.");
1
the original question is about Kotlin coroutines; this has nothing to do with Java's thread suspending
– P.J.Meisch
2 days ago
i presume concept would be same.
– surendrapanday
2 days ago
Suspending functions are vastly different from blocking functions!
– functionaldude
1 hour ago
add a comment |
Even though your question is unclear, I can say that finally is always executed, you are right, in doing so it tries to run a suspended function which by definition is locked until you call it back. By default, a suspend function for instance in Java, means execution is suspended. Finally block trying to execute without using resume() would throw an exception. Once, your function has been suspended, you need to use another proper function to revive function from executing. Credit goes to https://www.tutorialspoint.com/java/java_thread_control.htm for example of code.
1 public void suspend()
This method puts a thread in the suspended state and can be resumed using resume() method.
2 public void stop()
This method stops a thread completely.
3 public void resume()
This method resumes a thread, which was suspended using suspend() method.
4 public void wait()
Causes the current thread to wait until another thread invokes the notify().
5 public void notify()
Wakes up a single thread that is waiting on this object's monitor.
class RunnableDemo implements Runnable
public Thread t;
private String threadName;
boolean suspended = false;
RunnableDemo( String name)
threadName = name;
System.out.println("Creating " + threadName );
public void run()
System.out.println("Running " + threadName );
try
for(int i = 10; i > 0; i--)
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(300);
synchronized(this)
while(suspended)
wait();
catch (InterruptedException e)
System.out.println("Thread " + threadName + " interrupted.");
System.out.println("Thread " + threadName + " exiting.");
public void start ()
System.out.println("Starting " + threadName );
if (t == null)
t = new Thread (this, threadName);
t.start ();
void suspend()
suspended = true;
synchronized void resume()
suspended = false;
notify();
public class TestThread
public static void main(String args[])
RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();
RunnableDemo R2 = new RunnableDemo( "Thread-2");
R2.start();
try
Thread.sleep(1000);
R1.suspend();
System.out.println("Suspending First Thread");
Thread.sleep(1000);
R1.resume();
System.out.println("Resuming First Thread");
R2.suspend();
System.out.println("Suspending thread Two");
Thread.sleep(1000);
R2.resume();
System.out.println("Resuming thread Two");
catch (InterruptedException e)
System.out.println("Main thread Interrupted");
try
System.out.println("Waiting for threads to finish.");
R1.t.join();
R2.t.join();
catch (InterruptedException e)
System.out.println("Main thread Interrupted");
System.out.println("Main thread exiting.");
Even though your question is unclear, I can say that finally is always executed, you are right, in doing so it tries to run a suspended function which by definition is locked until you call it back. By default, a suspend function for instance in Java, means execution is suspended. Finally block trying to execute without using resume() would throw an exception. Once, your function has been suspended, you need to use another proper function to revive function from executing. Credit goes to https://www.tutorialspoint.com/java/java_thread_control.htm for example of code.
1 public void suspend()
This method puts a thread in the suspended state and can be resumed using resume() method.
2 public void stop()
This method stops a thread completely.
3 public void resume()
This method resumes a thread, which was suspended using suspend() method.
4 public void wait()
Causes the current thread to wait until another thread invokes the notify().
5 public void notify()
Wakes up a single thread that is waiting on this object's monitor.
class RunnableDemo implements Runnable
public Thread t;
private String threadName;
boolean suspended = false;
RunnableDemo( String name)
threadName = name;
System.out.println("Creating " + threadName );
public void run()
System.out.println("Running " + threadName );
try
for(int i = 10; i > 0; i--)
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(300);
synchronized(this)
while(suspended)
wait();
catch (InterruptedException e)
System.out.println("Thread " + threadName + " interrupted.");
System.out.println("Thread " + threadName + " exiting.");
public void start ()
System.out.println("Starting " + threadName );
if (t == null)
t = new Thread (this, threadName);
t.start ();
void suspend()
suspended = true;
synchronized void resume()
suspended = false;
notify();
public class TestThread
public static void main(String args[])
RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();
RunnableDemo R2 = new RunnableDemo( "Thread-2");
R2.start();
try
Thread.sleep(1000);
R1.suspend();
System.out.println("Suspending First Thread");
Thread.sleep(1000);
R1.resume();
System.out.println("Resuming First Thread");
R2.suspend();
System.out.println("Suspending thread Two");
Thread.sleep(1000);
R2.resume();
System.out.println("Resuming thread Two");
catch (InterruptedException e)
System.out.println("Main thread Interrupted");
try
System.out.println("Waiting for threads to finish.");
R1.t.join();
R2.t.join();
catch (InterruptedException e)
System.out.println("Main thread Interrupted");
System.out.println("Main thread exiting.");
answered 2 days ago
surendrapandaysurendrapanday
12411
12411
1
the original question is about Kotlin coroutines; this has nothing to do with Java's thread suspending
– P.J.Meisch
2 days ago
i presume concept would be same.
– surendrapanday
2 days ago
Suspending functions are vastly different from blocking functions!
– functionaldude
1 hour ago
add a comment |
1
the original question is about Kotlin coroutines; this has nothing to do with Java's thread suspending
– P.J.Meisch
2 days ago
i presume concept would be same.
– surendrapanday
2 days ago
Suspending functions are vastly different from blocking functions!
– functionaldude
1 hour ago
1
1
the original question is about Kotlin coroutines; this has nothing to do with Java's thread suspending
– P.J.Meisch
2 days ago
the original question is about Kotlin coroutines; this has nothing to do with Java's thread suspending
– P.J.Meisch
2 days ago
i presume concept would be same.
– surendrapanday
2 days ago
i presume concept would be same.
– surendrapanday
2 days ago
Suspending functions are vastly different from blocking functions!
– functionaldude
1 hour ago
Suspending functions are vastly different from blocking functions!
– functionaldude
1 hour ago
add a comment |
From my understanding, in a
finally-block, the exception, if it exists, is thrown after executing the entire block.
This is not true. If a finally block throws an exception, it causes the finally block to terminate abruptly with that exception. Any exception that was thrown within try is thus discarded. This is exactly what happens in your case: the finally block of the first child coroutine receives a CancellationException on the delay(1000) line. Thread.sleep(1000) is a blocking, non-cancellable function, therefore it doesn't observe the cancellation.
You probably mixed up this with the fact that, if the try block throws an exception, then first the complete finally block is executed before throwing the exception. The finally block is required to complete normally in order for this to happen.
So I believe you aren't describing any difference in the behavior of plain and suspendable functions.
add a comment |
From my understanding, in a
finally-block, the exception, if it exists, is thrown after executing the entire block.
This is not true. If a finally block throws an exception, it causes the finally block to terminate abruptly with that exception. Any exception that was thrown within try is thus discarded. This is exactly what happens in your case: the finally block of the first child coroutine receives a CancellationException on the delay(1000) line. Thread.sleep(1000) is a blocking, non-cancellable function, therefore it doesn't observe the cancellation.
You probably mixed up this with the fact that, if the try block throws an exception, then first the complete finally block is executed before throwing the exception. The finally block is required to complete normally in order for this to happen.
So I believe you aren't describing any difference in the behavior of plain and suspendable functions.
add a comment |
From my understanding, in a
finally-block, the exception, if it exists, is thrown after executing the entire block.
This is not true. If a finally block throws an exception, it causes the finally block to terminate abruptly with that exception. Any exception that was thrown within try is thus discarded. This is exactly what happens in your case: the finally block of the first child coroutine receives a CancellationException on the delay(1000) line. Thread.sleep(1000) is a blocking, non-cancellable function, therefore it doesn't observe the cancellation.
You probably mixed up this with the fact that, if the try block throws an exception, then first the complete finally block is executed before throwing the exception. The finally block is required to complete normally in order for this to happen.
So I believe you aren't describing any difference in the behavior of plain and suspendable functions.
From my understanding, in a
finally-block, the exception, if it exists, is thrown after executing the entire block.
This is not true. If a finally block throws an exception, it causes the finally block to terminate abruptly with that exception. Any exception that was thrown within try is thus discarded. This is exactly what happens in your case: the finally block of the first child coroutine receives a CancellationException on the delay(1000) line. Thread.sleep(1000) is a blocking, non-cancellable function, therefore it doesn't observe the cancellation.
You probably mixed up this with the fact that, if the try block throws an exception, then first the complete finally block is executed before throwing the exception. The finally block is required to complete normally in order for this to happen.
So I believe you aren't describing any difference in the behavior of plain and suspendable functions.
edited 5 mins ago
answered 31 mins ago
Marko TopolnikMarko Topolnik
147k19199326
147k19199326
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54965849%2fwhy-do-suspending-functions-throw-exceptions-in-finally%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown

1
share your code
– Radesh
2 days ago