Skip to content

Commit 09d95e9

Browse files
authored
Merge pull request #860 from sk1418/conditional-exception
[conditional-exception] conditional throwing
2 parents 17375c1 + afdb548 commit 09d95e9

File tree

4 files changed

+136
-0
lines changed

4 files changed

+136
-0
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
## Core Kotlin Exceptions
2+
3+
This module contains articles about core Kotlin Exceptions.
4+
5+
### Relevant articles:
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<modelVersion>4.0.0</modelVersion>
6+
<artifactId>core-kotlin-exceptions</artifactId>
7+
<name>core-kotlin-exceptions</name>
8+
<packaging>jar</packaging>
9+
10+
<parent>
11+
<groupId>com.baeldung</groupId>
12+
<artifactId>core-kotlin-modules</artifactId>
13+
<version>1.0.0-SNAPSHOT</version>
14+
</parent>
15+
</project>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
package com.baeldung.conditionalThrowing
2+
3+
import org.junit.jupiter.api.Test
4+
import org.junit.jupiter.api.assertThrows
5+
import kotlin.test.assertEquals
6+
7+
8+
class MyException(msg: String) : Exception(msg)
9+
10+
inline fun throwIf(throwCondition: Boolean, exProvider: () -> Exception) {
11+
if (throwCondition) throw exProvider()
12+
}
13+
14+
inline fun <T : Any?> T.mustHave(
15+
otherwiseThrow: (T) -> Exception = { IllegalStateException("mustHave check failed: $it") },
16+
require: (T) -> Boolean
17+
): T {
18+
if (!require(this)) throw otherwiseThrow(this)
19+
return this
20+
}
21+
22+
data class Player(val id: Int, val name: String, val score: Int)
23+
class InvalidPlayerException(message: String) : RuntimeException(message)
24+
25+
class ConditionalThrowingUnitTest {
26+
27+
@Test
28+
fun `when using require() then get expected results`() {
29+
val str = "a b c"
30+
assertThrows<IllegalArgumentException> {
31+
require(str.length > 10) { "The string is too short." }
32+
}
33+
34+
val upperStr = str.also {
35+
require(it.split(" ").size == 3) { "Format not supported" }
36+
}.uppercase()
37+
assertEquals("A B C", upperStr)
38+
39+
40+
var nullableValue: String? = null
41+
assertThrows<IllegalArgumentException> {
42+
requireNotNull(nullableValue) { "Null is not allowed" }
43+
}
44+
45+
nullableValue = "a b c"
46+
val uppercaseValue = requireNotNull(nullableValue).uppercase()
47+
assertEquals("A B C", uppercaseValue)
48+
}
49+
50+
@Test
51+
fun `when using check() then get expected results`() {
52+
val str = "a b c"
53+
assertThrows<IllegalStateException> {
54+
check(str.length > 10) { "The string is too short." }
55+
}
56+
57+
var nullableValue: String? = null
58+
assertThrows<IllegalStateException> {
59+
checkNotNull(nullableValue) { "Null is not allowed" }
60+
}
61+
62+
nullableValue = "a b c"
63+
val uppercaseValue = checkNotNull(nullableValue).uppercase()
64+
assertEquals("A B C", uppercaseValue)
65+
}
66+
67+
68+
@Test
69+
fun `when using takeIf() then get expected results`() {
70+
val str = "a b c"
71+
assertThrows<MyException> {
72+
str.takeIf { it.length > 10 } ?: throw MyException("The string is too short.")
73+
}
74+
75+
val nullIsValid: String? = null
76+
assertThrows<MyException> {
77+
nullIsValid.takeIf { true } ?: throw MyException("The string is too short.")
78+
}
79+
}
80+
81+
@Test
82+
fun `when using throwIf() then get expected results`() {
83+
val str = "a b c"
84+
assertThrows<MyException> {
85+
throwIf(str.length <= 10) { MyException("The string is too short.") }
86+
}
87+
88+
val uppercaseValue = str.also {
89+
throwIf(it.split(" ").size != 3) { MyException("Format not supported") }
90+
}.uppercase()
91+
assertEquals("A B C", uppercaseValue)
92+
}
93+
94+
95+
@Test
96+
fun `when using mustHave() then get expected results`() {
97+
val kai = Player(1, "Kai", -5)
98+
assertThrows<IllegalStateException> { kai.mustHave { it.score >= 0 } }
99+
.also { ex -> assertEquals("mustHave check failed: Player(id=1, name=Kai, score=-5)", ex.message) }
100+
101+
assertThrows<InvalidPlayerException> {
102+
kai.mustHave(
103+
require = { it.score >= 0 },
104+
otherwiseThrow = { InvalidPlayerException("Player [id=${it.id}, name=${it.name}] is invalid") }
105+
)
106+
}.also { ex -> assertEquals("Player [id=1, name=Kai] is invalid", ex.message) }
107+
108+
val liam = Player(2, "Liam", 42)
109+
val upperDescription = liam.mustHave(
110+
require = { it.score >= 0 },
111+
otherwiseThrow = { InvalidPlayerException("Player [id=${it.id}, name=${it.name}] is invalid") }
112+
).let { "${it.name} : ${it.score}".uppercase() }
113+
assertEquals("LIAM : 42", upperDescription)
114+
}
115+
}

core-kotlin-modules/pom.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
<module>core-kotlin-datastructures</module>
4949
<module>core-kotlin-datastructures-2</module>
5050
<module>core-kotlin-design-patterns</module>
51+
<module>core-kotlin-exceptions</module>
5152
<module>core-kotlin-io</module>
5253
<module>core-kotlin-lang</module>
5354
<module>core-kotlin-lang-2</module>

0 commit comments

Comments
 (0)