当前位置:网站首页>Talking about kotlin process exception handling mechanism
Talking about kotlin process exception handling mechanism
2022-06-30 09:01:00 【Byte station】
1. Preface
If this is the first time you've heard of someone linking exception handling to event distribution , I believe you will be the same as when I first came into contact with the exception handling mechanism of a coroutine , A face of meng . Not to mention that many of you here Android old hand , Even if it is Android Adorable new , I should know , Exception handling is try catch Such a simple thing , How can it be related to the complex event distribution mechanism ? Don't believe it's really related .
If you have been exposed to collaborative knowledge for some time , And we know that the exception handling mechanism of the collaboration process is different from the exception handling mechanism we have known in the past , But it doesn't quite work , I'll take you step by step to figure out what's going on .
If you have a good understanding of the process exception handling mechanism , So congratulations , I think at the current point in time , You have surpassed most people . I hope this article can be given to friends at different stages , Help in varying degrees .
Of course , This article does not cover event distribution in detail .Android Of View The structural concurrency of the system and the collaboration process is the same , Their corresponding data structures are tree.View Event distribution and coordination Cancel The communication mechanism is very similar , The depth traversal algorithm of the tree is used . For event distribution, please refer to Android Analysis of event distribution mechanism .
2. Exception trapping
Kotlin Exception capture and Java equally , use try catch You can catch exceptions . Let's take a simple example . adopt try catch Capture exception . Results the print "caught null pointer exception".

Start a process . Catch exceptions in the process body , The result is the same as expected , Print “caught null pointer exception”.

Suppose there is a method provided by a third party thirdApi.thirdApi Method starts a coroutine and does not catch an exception . As a result, the program crashes .

At first, I was confusedTo solve the above crash problem , Our first reaction is to call thirdApi Add try catch,so easy Well ! Run code , Silly eyes , The program still crashes .try catch encase CoroutineScope.launch Unable to catch exception ?
Although I don't understand why the above code can't catch exceptions , But I know there are CoroutineExceptionHandler Can handle exceptions , Try to catch exceptions as follows ? Results the print "caught null pointer exception".

Continue to look foolishIf you put exceptionHandler Put it in the second launch In the method , I can't catch the exception , The program crashed again .
Continue to look foolishIf you use coroutineScope Wrap the second launch Method , Things are different again , Results the print “caught exception in try catch exception null pointer exception”. The exception is try catch Capture , Rather than being exceptionHandler Capture .
Continue to look foolishIf you use supervisorScope Instead of coroutineScope, Things are different again , Results the print “caught exception in handler null pointer exception”. By exceptionHandler Captured .
stay 7 Based on the code , If you put try catch Get rid of , In the outer layer launch Add outerExceptionHandler Parameters . The result is “caught exception in outer handler null pointer exception”. The exception is outerExceptionHandler Captured .

Continue to look foolishstay 9 Based on the code of coroutineScope Replace with supervisorScope. The result is “caught exception in inner handler null pointer exception”. The exception is innerExceptionHandler Captured .
above 10 A scenario , Whether you are a beginner or a veteran of Xiecheng , I believe you've lost your head . A simple exception handling , How come there are so many scenes in the process of cooperation , And the results are different . If you don't master the exception handling logic of the coordination process , I dare not cooperate in the project . Otherwise, I don't know how the project will collapse .
Don't worry about the above scene , That's just my list 10 A scenario , In theory , These scenarios can 72 change , There are countless scenes . But everything is the same , Only master the principle , To be able to cope freely .
3. Principle of exception handling
stay Chat Job and SupervisorJob The difference between In this article, I briefly introduced the principle of exception handling . To understand the principle of exception handling, you must also understand structured concurrency , You can refer to Kotlin How does a coroutine create structured concurrency ?
The exception handling logic can be explained by workplace examples . Suppose the unspoken rule of the workplace is , Any employee made a mistake , The first thing is to report to the superior , If your superiors are willing to deal with your mistakes , Then the employees don't have to care , If the supervisor calls back the problem to the employee , Then the mistakes have to be handled by the employees themselves .
The following figure illustrates the exception handling mechanism as an example ,Job5 An exception occurred at ( Here refers to non CancellationException).
- Job5 First, the exception will be passed to Job2 Handle .Job2 There are two options , Select No. 1 to not handle the exception , Call the exception back to Job5,Job5 call handleJobException Method . Option 2 yes Job2 Select to handle the exception , Then the exception is passed to Job2 了 ,Job5 No more chance to handle exceptions .
- Job2 The logic for handling exceptions is the same as Job5, First, the exception will be passed to Job0.Job0 There are also two options , Return the call to Job2 Handle , call Job2 Of handleJobException Method or by Job0 Handle .
- Middle root of coordination process Job Will not handle exceptions , It will return the exception to the cause Job Handle . In this case Job0 Will give the exception to Job2 Handle .
- Job handleJobException The logic for handling exceptions is , First of all, judge the context Whether it has been set CoroutineExceptionHandler, If there is one, it should be handed over to CoroutineExceptionHandler Handling exceptions . If it is not set, it will be handed over to AndroidExceptionPreHandler Handle .
There are several points to pay attention to
- CancellationException Spread to the father Job, It must be called back . In other words , It does not affect the parent Job.
- SupervisorJob and supervisorScope Will also return the exception to the child Job Handle , Both of them can strangle the abnormality inside , Do not broadcast to the outside .
- coroutineScope and withContext You can put the exception of the coordination process rethrow, That is, they can be coated with try catch Capture .
4. Last
Finally, click on the question . Event distribution Down Event is a tree traversal algorithm ( Root right left ). Instead of Down event ( Such as Move、Up Other events ) It's based on TouchTarget The generated event linked list traverses the linked list . The coordination process is similar ,cancel event , First, cancel yourself and the child cooperation process , Is traversal according to the preorder ( Root left and right ), Then cancel the parent association ( The parent coroutine is also a preorder traversal cancellation ). Exception handling is based on child nodes -> The linked list traversal request of the parent node is abnormal . It's not too much to say that you are a mother . If you don't understand , It shows that your knowledge of data structure and algorithm is still relatively deficient , It is suggested to make up lessons .
Welcome to pay attention to the wechat official account with the same name of bytecode
边栏推荐
- 文件上传 upload 组件 on-success 事件,添加自定义参数
- Mmcv expanding CUDA operator beginner level chapter
- Esp32 things (x): other functions
- A troubleshooting of CPU bottom falling
- Rew acoustic test (III): generate test signal
- Raspberry pie 4B no screen installation system and networking using VNC wireless projection function
- Flink 数据偶尔数据积压导致checkpoint失败
- vite项目require语法兼容问题解决require is not defined
- 14岁懂社会-《关于“工作的幸福”这件事儿》读书笔记
- Six implementation methods of singleton mode
猜你喜欢

Qt连接神通数据库
![[data analysis and display]](/img/86/19260ee664769c98588d8b0783ef28.jpg)
[data analysis and display]

Rew acoustic test (III): generate test signal

Does the oscilloscope probe affect the measurement of capacitive load?

Opencv learning notes -day8 (keyboard typing (waitkey()); Wait for typing) action: triggers some action when the appropriate character is typed using the keyboard)

C accesses mongodb and performs CRUD operations

Implementing custom drawer component in quick application

Enhance the add / delete operation of for loop & iterator delete collection elements

Redis design and Implementation (II) | database (deletion strategy & expiration elimination strategy)

Opencv learning notes-day5 (arithmetic operation of image pixels, add() addition function, subtract() subtraction function, divide() division function, multiply() multiplication function
随机推荐
自制GIF动态图-gifcam
Tidb v6.0.0 (DMR): initial test of cache table - tidb Book rush
Be careful of this hole in transmittable thread local
Rew acoustic test (VI): signal and measurement
Flink Exception -- No ExecutorFactory found to execute the application
C#访问MongoDB并执行CRUD操作
Sort (simple description)
QT connection to Shentong database
Esp32 (IX): OTA function of function development
C # listbox how to get the selected content (search many invalid articles)
Flink Sql -- toAppendStream doesn‘t support consuming update and delete changes which
Opencv learning notes-day9 opencv's own color table operation (colormap coloraptypes enumeration data types and applycolormap() pseudo color function)
Flink sql -- No factory implements ‘org. apache. flink. table. delegation. ExecutorFactory‘.
JVM调优相关命令以及解释
证券开户的优惠怎样才能得到?在线开户安全?
C#訪問SQL Server數據庫兩種方式的比較(SqlDataReader vs SqlDataAdapter)
Implementing custom drawer component in quick application
Mmdet line by line deltaxywhbboxcoder
PHP API to obtain QR code and combine to generate pictures
Detailed explanation of pipline of mmdetection