引言

从前面我们可以大致了解了协程的玩法,如果一个协程中使用子协程,那么该协程会等待子协程执行结束后才真正退出,而达到这种效果的原因就是协程上下文,上下文贯穿了协程的生命周期,这套思想和我们app的上下文很像

在开始真正了解协程上下文之前,我们先来看看下面的例子

下面的图代表了一个协程a的生命,就像一条从上至下的直线,它的生命只有100ms

当我们在a协程延迟函数100ms之前开启一个子协程b,b做了200ms的事情,如果不考虑调度消耗的时间,那么a协程的生命也会延长成200ms

代码验证下:

fun `test context life`() = runBlocking {
    //定义一个作用域
    val a = CoroutineScope(Dispatchers.Default)
    val startTime = System.currentTimeMillis()
    //协程a开启
    val jobA = a.launch {
        //子协程b开启
        val jobB = launch {
            delay(200)
        }
        delay(100)
    }
    //等待协程a结束
    jobA.join()
    val endTime = System.currentTimeMillis()
    println(endTime - startTime)
}
fun main() {
    `test context life`()
}

结果:237

如果我们把子协程b增加到delay 300ms,那么结果也会相应的变为:

323

通过上面的列子,来对协程上下文的有一个初步概念:可以说协程的生命周期,就是上下文的生命周期

协程拥有很多新的概念,很多人一开始接触就能难理解(包括我自己),这些概念都是在上下文的基础上引申而来的,所以我一再强调它的重要性,协程的上下文必须理解透,才能玩好协程,接下来我们来真正了解协程上下文

一、协程上下文

1.CoroutineContext

协程上下文有以下几项构成,它们都是实现了CoroutineContext.Element接口,有些是实现了AbstractCoroutineContextElement接口,而AbstractCoroutineContextElement继承CoroutineContext.Element接口

1.Job:控制协程的生命周期,也是我们能拿到操作协程任务的唯一对象

2.CoroutineDispatcher:就是之前介绍的调度器

3.CoroutineName:协程的名字,一般输出日志用的

4.CoroutineExceptionHandler:处理未捕获的异常

协程上下文实现了运算符重载,我们可以用 号来组合一个CoroutineContext的元素

2.CorountineScope

一般情况下,协程体内所有的子协程,都继承至根协程,协程的继承的关系不是我们所了解的类的继承关系,而是父协程和子协程的生命周期关系,还记得我们上面举得例子么,除非在协程体内自己手动创建协程作用域,即:创建一个全新的协程上下文,我们之前已经介绍过了:

CorountineScope:创建协程作用域,新起线程,观察源码,内部实际实例化的是ContextScope,ContextScope被internal修饰,内部使用,我们实例化不了

其他的实际上都是继承父协程上下文,或者内部实例化了ContextScope:

1.runBlocking:将主线程转变为协程,会阻塞主线程,实际上用的是一个EmptyCoroutineContext作为上下文,它是一个主线程的协程上下文,静态的全局变量,我们其实就可以理解成是主线程
2.GlobalScope:也是用的EmptyCoroutineContext
3.MainScope:使用ContextScope构造了新的上下文
4.coroutineScope:继承的父协程上下文,不能算是全新的协程
等等

3.子协程继承父协程

子协程继承父协程时,除了Job会自动创建新的实例外,其他3项的不手动指定的话,都会自动继承父协程的,Job对应的是协程任务,每次新的任务肯定都是新的Job对象

有了这些概念后,接下来通过代码,再熟悉巩固下

例子1:

fun `test context life1`() = runBlocking {
    //定义一个作用域
    val a = CoroutineScope(Dispatchers.Default)
    //协程a开启
    val jobA = a.launch {
        delay(100)
        println("jobA finished")
    }
    println("main finished")
}

结果:
main finished

由于a是一个根协程,全新的上下文,runBlocking 是主线程的协程上下文,所以当a开启任务时,不会阻塞主线程,当我们的进程都跑完了,jobA finished肯定不会打印了

例子2:

fun `test context life2`() = runBlocking {
    //定义一个作用域
    val a = CoroutineScope(Dispatchers.Default)
    //协程a开启
    val jobA = a.launch {
        delay(100)
        println("jobA finished")
    }
    jobA.join()
    println("main finished")
}

结果:
jobA finished
main finished

我们在主协程(主线程的协程)中,手动调用jobA的join方法,那么主线程就会阻塞,直到jobA执行完毕。这个和我们的多线程操作是一样的,主线程等待A线程执行完后再往后执行

例子3:

fun `test context life3`() = runBlocking {
    launch {
        delay(100)
        println("jobA finished")
    }
    println("main finished")
}

结果:
main finished
jobA finished

这回我们没有构建新的协程作用域,而是在根协程中直接使用子协程的方式,当然了,协程的上下文继承关系,使得我们的主协程等待子协程执行完毕后才结束生命

例子4:

fun `test context life4`() = runBlocking {
    launch(Dispatchers.IO   CoroutineName("jobA")) {
        delay(100)
        println("${coroutineContext[CoroutineName]}  finished")
    }
    println("main finished")
}

结果:
main finished
CoroutineName(jobA) finished

即使我们指定了子协程的调度器和协程名,也不会影响协程上下文继承关系,主协程还是会等待子协程执行完毕后才结束生命

如果你已经完全理解了,那么就可以知道以上例子使用async启动也是一样的效果

二、协程的异常传递

1.协程的异常传播

协程的异常传播也是遵循了协程上下文的机制,除了取消异常(CancellationException)外,当一个协程有了异常,如果没有主动捕获异常,那么异常会向上传播,直到根协程,子协程的异常都会导致根协程退出,自然其他子协程也会退出

例子1:

fun `test coroutineScope exception1`() = runBlocking {
    val job1 = launch {
        delay(2000)
        println("job finished")
    }
    val job2 = launch {
        delay(1000)
        println("job2 finished")
        throw IllegalArgumentException()
    }
    delay(3000)
    println("finished")
}

结果:

job2 finished
Exception in thread "main" java.lang.IllegalArgumentException
    at com.aruba.mykotlinapplication.coroutine.ExceptionTestKt$test coroutineScope exception1$1$job2$1.invokeSuspend(exceptionTest.kt:46)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.ResumeModeKt.resumeMode(ResumeMode.kt:67)
    at kotlinx.coroutines.DispatchedKt.resume(Dispatched.kt:309)
    at kotlinx.coroutines.DispatchedKt.dispatch(Dispatched.kt:298)
    at kotlinx.coroutines.CancellableContinuationImpl.dispatchResume(CancellableContinuationImpl.kt:250)
    at kotlinx.coroutines.CancellableContinuationImpl.resumeImpl(CancellableContinuationImpl.kt:260)
    at kotlinx.coroutines.CancellableContinuationImpl.resumeUndispatched(CancellableContinuationImpl.kt:332)
    at kotlinx.coroutines.EventLoopImplBase$DelayedResumeTask.run(EventLoop.kt:298)
    at kotlinx.coroutines.EventLoopImplBase.processNextEvent(EventLoop.kt:116)
    at kotlinx.coroutines.BlockingCoroutine.joinBlocking(Builders.kt:80)
    at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking(Builders.kt:54)
    at kotlinx.coroutines.BuildersKt.runBlocking(Unknown Source)
    at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking$default(Builders.kt:36)
    at kotlinx.coroutines.BuildersKt.runBlocking$default(Unknown Source)
    at com.aruba.mykotlinapplication.coroutine.ExceptionTestKt.test coroutineScope exception1(exceptionTest.kt:37)
    at com.aruba.mykotlinapplication.coroutine.ExceptionTestKt.main(exceptionTest.kt:54)
    at com.aruba.mykotlinapplication.coroutine.ExceptionTestKt.main(exceptionTest.kt)

Process finished with exit code 1

job2 1000ms后就发生了异常,导致job1和父协程都直接退出

2.不同上下文(没有继承关系)之间协程异常会怎么样?

例子1:

fun `test coroutineScope exception2`() = runBlocking {
    val job1 = launch {
        delay(2000)
        println("job finished")
    }
    val job2 = CoroutineScope(Dispatchers.IO).launch{
        delay(1000)
        println("job2 finished")
        throw IllegalArgumentException()
        println("new CoroutineScope finished")
    }
    delay(3000)
    println("finished")
}

结果:

job2 finished
Exception in thread "DefaultDispatcher-worker-2" java.lang.IllegalArgumentException
    at com.aruba.mykotlinapplication.coroutine.ExceptionTestKt$test coroutineScope exception1$1$job2$1.invokeSuspend(exceptionTest.kt:46)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:238)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:594)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.access$runSafely(CoroutineScheduler.kt:60)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:742)
job finished
finished

Process finished with exit code 0

可以看出不同根协程的协程之间,异常并不会自动传递,我们的主线程上下文协程正常执行

再看例子2:

fun `test coroutineScope exception3`() = runBlocking {
    val job1 = launch {
        delay(2000)
        println("job finished")
    }
    val job2 = CoroutineScope(Dispatchers.IO).async{
        delay(1000)
        println("job2 finished")
        throw IllegalArgumentException()
        println("new CoroutineScope finished")
    }
    delay(3000)
    println("finished")
}

结果:
job2 finished
job finished
finished

和例子1的唯一区别是,使用了全新上下文的协程使用了async启动,哈哈,这就奇怪了,为什么会这样?

3.向用户暴露异常

还记得async启动的协程返回的是一个Deferred么,它可以使用await函数,来获取协程运行结果。那么试想一下,如果我就是想要一个协程执行完返回一个异常呢?

所以async中的异常会作为返回值,返回给调用await函数

fun `test coroutineScope exception4`() = runBlocking {
    val job1 = launch {
        delay(2000)
        println("job finished")
    }
    val job2 = CoroutineScope(Dispatchers.IO).async{
        delay(1000)
        println("job2 finished")
        throw IllegalArgumentException()
        println("new CoroutineScope finished")
    }
    job2.await()
    delay(3000)
    println("finished")
}

结果:

job2 finished
Exception in thread "main" java.lang.IllegalArgumentException
    at com.aruba.mykotlinapplication.coroutine.ExceptionTestKt$test coroutineScope exception4$1$job2$1.invokeSuspend(exceptionTest.kt:96)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:238)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:594)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.access$runSafely(CoroutineScheduler.kt:60)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:742)

Process finished with exit code 1

await的时候出现异常了,当然会导致协程退出,我们可以在await的时候捕获下这个异常,就不会影响主线程上下文的协程运行了

fun `test coroutineScope exception4`() = runBlocking {
    val job1 = launch {
        delay(2000)
        println("job finished")
    }
    val job2 = CoroutineScope(Dispatchers.IO).async {
        delay(1000)
        println("job2 finished")
        throw IllegalArgumentException()
        println("new CoroutineScope finished")
    }
    try {
        job2.await()
    } catch (e: Exception) {
        e.printStackTrace()
    }
    delay(3000)
    println("finished")
}

结果:

job2 finished
java.lang.IllegalArgumentException
    at com.aruba.mykotlinapplication.coroutine.ExceptionTestKt$test coroutineScope exception4$1$job2$1.invokeSuspend(exceptionTest.kt:96)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:238)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:594)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.access$runSafely(CoroutineScheduler.kt:60)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:742)
job finished
finished

Process finished with exit code 0

值得注意的是,同一继承关系下的协程使用await并无法捕获异常,还是会遵循第一条,导致整个协程生命周期结束

fun `test coroutineScope exception5`() = runBlocking {
    val job2 = CoroutineScope(Dispatchers.IO).launch {
        val job1 = launch {
            delay(2000)
            println("job finished")
        }
        val job3 = async {
            delay(1000)
            println("job3 finished")
            throw IllegalArgumentException()
        }
        try {
            job3.await()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        delay(2000)
        println("job2 finished")
    }
    job2.join()
    println("finished")
}

结果:

job3 finished
java.lang.IllegalArgumentException
    at com.aruba.mykotlinapplication.coroutine.ExceptionTestKt$test coroutineScope exception5$1$job2$1$job3$1.invokeSuspend(exceptionTest.kt:119)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:238)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:594)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.access$runSafely(CoroutineScheduler.kt:60)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:742)
Exception in thread "DefaultDispatcher-worker-1" java.lang.IllegalArgumentException
    at com.aruba.mykotlinapplication.coroutine.ExceptionTestKt$test coroutineScope exception5$1$job2$1$job3$1.invokeSuspend(exceptionTest.kt:119)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:238)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:594)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.access$runSafely(CoroutineScheduler.kt:60)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:742)
finished

Process finished with exit code 0

可以发现job3.await()的try catch并没有生效,所以向用户暴露异常只适用于不同上下文(没有继承关系)的协程

三、协程的异常处理

使用SupervisorJob

如果想要一个协程出现异常后,不影响其继承关系中的其他协程,可以使用SupervisorJob

fun `test SupervisorJob exception`() = runBlocking {
    val job1 = launch {
        delay(2000)
        println("job finished")
    }
    val job2 = async(SupervisorJob()) {
        delay(1000)
        println("job2 finished")
        throw IllegalArgumentException()
    }
    delay(3000)
    println("finished")
}

结果:
job2 finished
job finished
finished

可以看到,job2的异常并没有影响其他继承关系的协程的执行

SupervisorScope,这个我们前面已经用过了,就不重复介绍了

异常捕获器CoroutineExceptionHandler

协程上下文的4项之一,可以用CrashHandler理解,不过它并不能阻止协程的退出,只能够获取异常的信息

它使用有两个条件:

1.异常是自动抛出异常(launch)

2.实例化CoroutineScope的时候指定异常捕获器 或者 在一个根协程中

例子1:

fun `test SupervisorHandler exception1`() = runBlocking {
    val handler = CoroutineExceptionHandler { _, throwable ->
        println("caught: $throwable")
    }
    val scope = CoroutineScope(handler)
    val job1 = scope.launch {
        val job2 = launch {
            delay(1000)
            println("job2 finished")
            throw IllegalArgumentException()
        }
        delay(2000)
        println("job finished")
    }
    delay(4000)
    println("finished")
}

结果:
job2 finished
caught: java.lang.IllegalArgumentException
finished

job2抛出了异常,被捕获到了,但是scope的其他协程随之生命周期也都结束了

例子2:

fun `test SupervisorHandler exception2`() = runBlocking {
    val handler = CoroutineExceptionHandler { _, throwable ->
        println("caught: $throwable")
    }
    val scope = CoroutineScope(Dispatchers.Default)
    val job1 = scope.launch(handler) {
        val job2 = launch {
            delay(1000)
            println("job2 finished")
            throw IllegalArgumentException()
        }
        delay(2000)
        println("job finished")
    }
    delay(4000)
    println("finished")
}

结果:
job2 finished
caught: java.lang.IllegalArgumentException
finished

和例子1相同,因为我们handler指定在了根协程

例子3:

fun `test SupervisorHandler exception3`() = runBlocking {
    val handler = CoroutineExceptionHandler { _, throwable ->
        println("caught: $throwable")
    }
    val scope = CoroutineScope(Dispatchers.Default)
    val job1 = scope.launch {
        val job2 = launch(handler) {
            delay(1000)
            println("job2 finished")
            throw IllegalArgumentException()
        }
        delay(2000)
        println("job finished")
    }
    delay(4000)
    println("finished")
}

结果:

job2 finished
Exception in thread "DefaultDispatcher-worker-4" java.lang.IllegalArgumentException
    at com.aruba.mykotlinapplication.coroutine.ExceptionTestKt$test SupervisorHandler exception$1$job1$1$job2$1.invokeSuspend(exceptionTest.kt:161)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:238)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:594)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.access$runSafely(CoroutineScheduler.kt:60)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:742)
finished

Process finished with exit code 0

handler不是在根协程中,不能捕获

如果一个子协程会抛出异常,那么对它进行等待时(join或await),包裹一层try catch 会出现意料之外的事

例子4:

fun `test SupervisorHandler exception4`() = runBlocking {
    val handler = CoroutineExceptionHandler { _, throwable ->
        println("caught: $throwable")
    }
    val scope = CoroutineScope(Dispatchers.Default)
    val job1 = scope.launch(handler) {
        val job2 = launch {
            delay(1000)
            println("job2 finished")
            throw IllegalArgumentException()
        }
        try {
            job2.join()
        }catch (e:Exception){
        }
//        val job3 = scope.launch {
//            println("job3 finished")
//        }
        println("job delay")
        delay(2000)
        for(i in 0..10){
            println(i)
        }
        println("job finished")
    }
    delay(4000)
    println("finished")
}

结果:
job2 finished
job delay
caught: java.lang.IllegalArgumentException
finished

如果把scope根协程中的delay函数注释掉,会怎么样呢?

fun `test SupervisorHandler exception4`() = runBlocking {
    val handler = CoroutineExceptionHandler { _, throwable ->
        println("caught: $throwable")
    }
    val scope = CoroutineScope(Dispatchers.Default)
    val job1 = scope.launch(handler) {
        val job2 = launch {
            delay(1000)
            println("job2 finished")
            throw IllegalArgumentException()
        }
        try {
            job2.join()
        }catch (e:Exception){
        }
//        val job3 = scope.launch {
//            println("job3 finished")
//        }
        println("job delay")
//        delay(2000)
        for(i in 0..10){
            println(i)
        }
        println("job finished")
    }
    delay(4000)
    println("finished")
}

结果:
job2 finished
job delay
0
1
2
3
4
5
6
7
8
9
10
job finished
caught: java.lang.IllegalArgumentException

如果不包裹try catch 那么println("job delay")都不会执行

由例子4和例子5,我们可以推断,如果子协程有异常发生了,我们在等待时捕获异常后,根协程执行了挂起函数,那么它会直接中断,不执行挂起函数以下的代码,如果没有挂起函数,那么后面的代码还是会执行

为了加强验证这点,我们使用Thread.sleep(2000)替换delay函数测试下:

fun `test SupervisorHandler exception4`() = runBlocking {
    val handler = CoroutineExceptionHandler { _, throwable ->
        println("caught: $throwable")
    }
    val scope = CoroutineScope(Dispatchers.Default)
    val job1 = scope.launch(handler) {
        val job2 = launch {
            delay(1000)
            println("job2 finished")
            throw IllegalArgumentException()
        }
        try {
            job2.join()
        }catch (e:Exception){
        }
//        val job3 = scope.launch {
//            println("job3 finished")
//        }
        println("job delay")
//        delay(2000)
        Thread.sleep(2000)
        for(i in 0..10){
            println(i)
        }
        println("job finished")
    }
    delay(4000)
    println("finished")
}

结果还是和例子5一样:
job2 finished
job delay
0
1
2
3
4
5
6
7
8
9
10
job finished
caught: java.lang.IllegalArgumentException
finished

Process finished with exit code 0

其实出现这个情况,和我们之前取消协程是一样的,出现异常后会开始取消协程,但是CPU密集型的代码还会执行,但是遇到挂起函数就会抛一个CancellationException,导致协程结束运行,如果我们在挂起函数加上try catch打印,那么我们就可以看到CancellationException了

例子6,把job3的注释放开:

fun `test SupervisorHandler exception4`() = runBlocking {
    val handler = CoroutineExceptionHandler { _, throwable ->
        println("caught: $throwable")
    }
    val scope = CoroutineScope(Dispatchers.Default)
    val job1 = scope.launch(handler) {
        val job2 = launch {
            delay(1000)
            println("job2 finished")
            throw IllegalArgumentException()
        }
        try {
            job2.join()
        }catch (e:Exception){
        }
        val job3 = scope.launch {
            println("job3 finished")
        }
        println("job delay")
        delay(2000)
//        Thread.sleep(2000)
        for(i in 0..10){
            println(i)
        }
        println("job finished")
    }
    delay(4000)
    println("finished")
}

结果:

job2 finished
job delay
caught: java.lang.IllegalArgumentException
Exception in thread "DefaultDispatcher-worker-1" java.lang.IllegalArgumentException
    at com.aruba.mykotlinapplication.coroutine.ExceptionTestKt$test SupervisorHandler exception4$1$job1$1$job2$1.invokeSuspend(exceptionTest.kt:227)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:238)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:594)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.access$runSafely(CoroutineScheduler.kt:60)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:742)
finished

Process finished with exit code 0

显然有异常没有被捕获,很明显这个异常是调用job3时输出的,由此又可以推断出,如果在等待任务结束时,任务出现异常并且手动捕获异常后,再启动子协程时,也会抛出异常,并且不可捕获
注意:新版本kotlin已修复这个bug,不会抛出异常了

Android中全局异常的处理

最后,感谢动脑学院Jason老师出的kotlin协程教程,得到了很多理解和启发

以上就是kotlin 协程上下文异常处理详解的详细内容,更多关于kotlin 协程上下文异常处理的资料请关注Devmax其它相关文章!

kotlin 协程上下文异常处理详解的更多相关文章

  1. ios – 使用swift进行异常处理

    catch来处理它.如果故事板中没有视图控制器,则无法执行任何操作.这是程序员的错误,创建它的人应该处理这些问题.你不能因为这种错误而责怪iOS运行时.

  2. Swift没有异常处理,遇到功能性错误怎么办?

    本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请发送邮件至dio@foxmail.com举报,一经查实,本站将立刻删除。

  3. Swift41/90Days - 面向轨道编程 - Swift 中的异常处理

    问题在开发过程中,异常处理算是比较常见的问题了。我们把下面那根Failure的线路扩展一下,便会看到两条平行的线路,这便是“双轨模型”,这是用“面向轨道编程”思想解决异常处理的理论基础。这就是“面向轨道编程”。也就是说具体的业务只需要处理灰色部分的逻辑:“面向轨道”编程确实给我们提供了一个很有趣的思路。比如ValueTransformation.swift这个真实的完整案例,以及antitypical/Result这个封装完整的Result库。面向铁轨,春暖花开。

  4. 面向轨道编程 - Swift 中的异常处理

    本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请发送邮件至dio@foxmail.com举报,一经查实,本站将立刻删除。

  5. swift详解之十-------------异常处理、类型转换 ( Any and AnyObject )

    异常处理、类型转换注:本文为作者倾心整理,希望对大家有所帮助!在swift中,错误用复合ErrorType协议的值表示。swift处理异常和别的语言不同的是swift不会展开调用堆栈。在swift中throw语句的性能几乎和return一样通过try!所以上面的例子还能这么写结果是一模一样的Any和AnyObject的类型Swift为不确定类型提供了两种特殊类型别名:AnyObject可以代表任何class类型的实例。Any可以表示任何类型,包括方法类型。

  6. Swift2网络操作和异常处理

    相信写过Swift的人应该都知道Alamofire,它是AFNetworking的Swift版本,同一个作者写的。"的哲学,不过Swift一直很强调安全性,Apple显然也并不仅仅满足于让Swift困守iOS开发领域,加上早就公布了年底要开源,大家也很期待它作为一门通用编程语言在其他领域的作为。从各方面来看,Swift2.0增加了对异常处理的支持都在情理之中。在我看来异常处理最重要的用途有两点:写底层框架的时候可以抛出一些异常让框架的使用者去处理,这样框架会显得更加灵活。

  7. Swift 2.0 异常处理

    WWDC2015宣布了新的Swift2.0.这次重大更新给Swift提供了新的异常处理方法。在Swift中,guard有点像if但是他们有两个非常重要的区别guard必须强制有else语句只有在guard审查的条件成立,guard之后的代码才会运行。所以,使用catch你可以对异常的解析进行更为高级的处理7MyError.NotExist{//dealwithnotexistMyError.OutOfRange{//dealwithnotexist}这里值得提一下在Swift2.0中一个跟异常处理没有关系

  8. swift注意点

    如果我们想要像Objective-C里那样定义可选的接口方法,就需要将接口本身定义为Objective-C的,也即在protocol定义之前加上@objc。另外和Objective-C中的@optional不同,我们使用没有@符号的关键字optional来定义可选方法//swift中的错误处理,Objective-C没有原生的异常处理机制。后来通过添加NSException类,还有NS_DURING,NS_HANDLER和NS_ENDHANDLER宏才有了异常处理。这种方案现在被称为“经典的异常处理”,还

  9. Swift2.0-异常处理Exception handler

    Swift2.0-异常处理前言关于我们为什么要使用异常处理,请看百度百科为我们作出的描述,想要更详细的资料请点这里以上摘自百度百科:关联,在Objective-C中,异常处理一般都是使用NSError类接收异常和抛出异常,使用方法像这样不得不说,Swift的异常处理更为优雅,下面会重点介绍。去执行该函数不建议使用try!

  10. Swift try 异常处理机制

    不处理异常如果我不想处理异常怎么办,或者说,我非常确定某个方法或者函数虽然声明会抛出异常,但是我自己知道我在使用时候是绝对不会抛出任何异常的。当然,如果你使用try!,而你的方法或者函数抛出了异常,那么你会得到一个运行中异常所以我们开发者需要慎用哦。

随机推荐

  1. Flutter 网络请求框架封装详解

    这篇文章主要介绍了Flutter 网络请求框架封装详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  2. Android单选按钮RadioButton的使用详解

    今天小编就为大家分享一篇关于Android单选按钮RadioButton的使用详解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧

  3. 解决android studio 打包发现generate signed apk 消失不见问题

    这篇文章主要介绍了解决android studio 打包发现generate signed apk 消失不见问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

  4. Android 实现自定义圆形listview功能的实例代码

    这篇文章主要介绍了Android 实现自定义圆形listview功能的实例代码,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  5. 详解Android studio 动态fragment的用法

    这篇文章主要介绍了Android studio 动态fragment的用法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  6. Android用RecyclerView实现图标拖拽排序以及增删管理

    这篇文章主要介绍了Android用RecyclerView实现图标拖拽排序以及增删管理的方法,帮助大家更好的理解和学习使用Android,感兴趣的朋友可以了解下

  7. Android notifyDataSetChanged() 动态更新ListView案例详解

    这篇文章主要介绍了Android notifyDataSetChanged() 动态更新ListView案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下

  8. Android自定义View实现弹幕效果

    这篇文章主要为大家详细介绍了Android自定义View实现弹幕效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  9. Android自定义View实现跟随手指移动

    这篇文章主要为大家详细介绍了Android自定义View实现跟随手指移动,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  10. Android实现多点触摸操作

    这篇文章主要介绍了Android实现多点触摸操作,实现图片的放大、缩小和旋转等处理,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

返回
顶部