Skip to content

Commit 954be11

Browse files
authored
error handling (#837)
* commit * commit * commit * commit * commit * commit * commit * commit
1 parent e9abcca commit 954be11

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
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+
}

0 commit comments

Comments
 (0)