在使用suspendCoroutine构建suspend函数时,需要使用try-catch块来捕获它可能抛出的异常。这个异常通常被称作CancellationException。以下是一个简单的示例,它演示了如何使用try-catch捕获异常:
suspend fun mySuspendFunc() = suspendCoroutine
在上面的例子中,如果执行异步操作抛出了一个异常,try-catch块将捕获它,并使用resumeWithException()方法将它转换成CancellationException。这样,调用协程的代码就可以获取到异常,并进行适当的处理。