当前位置:网站首页>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
边栏推荐
- Implementing custom drawer component in quick application
- Opencv learning notes -day2 (implemented by the color space conversion function cvtcolar(), and imwrite image saving function imwrite())
- Evaluation standard for audio signal quality of intelligent speakers
- How can we get a satisfactory salary? These routines still need to be mastered
- Abstract factory pattern
- Resnet50+fpn for mmdet line by line code interpretation
- Coredata acquisition in swift sorting, ascending, descending
- Interference source current spectrum test of current probe
- Flink SQL 自定义 Connector
- 【付费推广】常见问题合集,推荐榜单FAQ
猜你喜欢

Opencv learning notes -day13 pixel value statistics calculation of maximum and minimum values, average values and standard deviations (use of minmaxloc() and meanstddev() functions)

Flink SQL 自定义 Connector

Sort (simple description)

Set, map and modularity

Flink SQL custom connector

Bottomsheetbehavior principle of realizing the home page effect of Gaode map

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

Metasploit practice - SSH brute force cracking process

Opencv learning notes-day14 drawing of image geometry (rect class rotatedrect class, rectangle drawing rectangle circle drawing circular function line drawing line function ellipse drawing elliptic fu

Redis design and Implementation (V) | sentinel sentry
随机推荐
Detailed explanation of pytoch's scatter function
vite项目require语法兼容问题解决require is not defined
codeforces每日5题(均1700)-第三天
Opencv learning notes -day3 (mat object and creation related operations mat:: clone(), mat:: copyto(), mat:: zeros(), mat:: ones(), scalar()...)
Be careful of this hole in transmittable thread local
Opencv learning notes -day2 (implemented by the color space conversion function cvtcolar(), and imwrite image saving function imwrite())
Opencv learning notes-day14 drawing of image geometry (rect class rotatedrect class, rectangle drawing rectangle circle drawing circular function line drawing line function ellipse drawing elliptic fu
How can I get the discount for opening a securities account? Is online account opening safe?
Based on svelte3 X desktop UI component library svelte UI
Opencv learning notes -day1 (image reading display imread, imshow, namedwindow)
Esp32 things (x): other functions
mysql基础入门 动力节点[老杜]课堂作业
自制GIF动态图-gifcam
Self made GIF dynamic graph -gifcam
Resnet50+fpn for mmdet line by line code interpretation
VIM from dislike to dependence (21) -- cross file search
Axure制作菜单栏效果
File upload component on success event, add custom parameters
Flink 数据偶尔数据积压导致checkpoint失败
Occasionally, Flink data is overstocked, resulting in checkpoint failure