File tree Expand file tree Collapse file tree 1 file changed +62
-0
lines changed
core-kotlin-modules/core-kotlin-concurrency-3/src/main/java/com/baeldung/errorhandling Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com.baeldung.errorhandling
2
+
3
+ import kotlinx.coroutines.*
4
+
5
+ fun main () = runBlocking {
6
+ launch {
7
+ try {
8
+ val result = 10 / 0
9
+ println (" Result: $result " )
10
+ } catch (e: ArithmeticException ) {
11
+ println (" Caught an ArithmeticException: $e " )
12
+ }
13
+ }
14
+ delay(1000 )
15
+ }
16
+
17
+ fun main1 () {
18
+ runBlocking {
19
+ try {
20
+ coroutineScope {
21
+ launch {
22
+ delay(100 )
23
+ throw CustomException (" An exception occurred!" )
24
+ }
25
+ launch {
26
+ delay(200 )
27
+ println (" This coroutine completes successfully." )
28
+ }
29
+ }
30
+ } catch (e: CustomException ) {
31
+ println (" Caught exception: ${e.message} " )
32
+ }
33
+ }
34
+ }
35
+
36
+ class CustomException (message : String ) : Exception(message)
37
+
38
+ fun main2 () = runBlocking {
39
+ val exceptionHandler = CoroutineExceptionHandler { _, exception ->
40
+ println (" Caught an exception: ${exception.message} " )
41
+ }
42
+ supervisorScope {
43
+ val job1 = launch(exceptionHandler) {
44
+ delay(100 )
45
+ println (" This coroutine completes successfully." )
46
+ }
47
+ val job2 = launch(exceptionHandler) {
48
+ throw Exception (" An exception occurred!" )
49
+ }
50
+ listOf (job1, job2).joinAll()
51
+ }
52
+ }
53
+ fun main3 () = runBlocking {
54
+ val exceptionHandler = CoroutineExceptionHandler { _, exception ->
55
+ println (" Caught global exception: ${exception.message} " )
56
+ }
57
+ val job = GlobalScope .launch(exceptionHandler) {
58
+ delay(100 )
59
+ throw CustomException (" An exception occurred!" )
60
+ }
61
+ job.join()
62
+ }
You can’t perform that action at this time.
0 commit comments