Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,690 questions

55,449 answers

573 users

How to handle invalid argument in Kotlin

4 Answers

0 votes
fun checkNumber(num: Int) {
    require(num >= 0) { "Negative numbers are not allowed" }
    println("Number: $num")
}

fun main() {
    checkNumber(8)  // Works fine
    checkNumber(-1)  // Throws IllegalArgumentException
}


 
/*
run:
 
Number: 8
Exception in thread "main" java.lang.IllegalArgumentException: Negative numbers are not allowed
 
*/

 



answered May 21, 2025 by avibootz
0 votes
fun validateAge(age: Int) {
    check(age >= 18) { "Age must be 18 or older" }
    println("Valid age: $age")
}

fun main() {
    validateAge(21)  // Works fine
    validateAge(16)  // Throws IllegalStateException
}


 
/*
run:
 
Valid age: 21
Exception in thread "main" java.lang.IllegalStateException: Age must be 18 or older
 
*/

 



answered May 21, 2025 by avibootz
0 votes
fun divide(a: Int, b: Int): Int {
    if (b == 0) throw IllegalArgumentException("Division by zero is not allowed")
    return a / b
}

fun main() {
    try {
        println(divide(800, 4))  // Works fine
        println(divide(7, 0))  // Throws exception
    } catch (e: IllegalArgumentException) {
        println("Error: ${e.message}")
    }
}


 
/*
run:
 
200
Error: Division by zero is not allowed
 
*/

 



answered May 21, 2025 by avibootz
0 votes
fun getPositiveNumber(num: Int?): Int {
    return num?.takeIf { it > 0 } ?: throw IllegalArgumentException("Number must be positive")
}

fun main() {
    println(getPositiveNumber(891))  // Works fine
    println(getPositiveNumber(-4))  // Throws exception
}


 
/*
run:
 
891
Exception in thread "main" java.lang.IllegalArgumentException: Number must be positive
 
*/

 



answered May 21, 2025 by avibootz

Related questions

4 answers 374 views
4 answers 373 views
4 answers 336 views
3 answers 279 views
3 answers 281 views
6 answers 521 views
...