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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,988 questions

51,933 answers

573 users

How to handle invalid argument in C++

4 Answers

0 votes
#include <iostream>
#include <stdexcept>

void printNumber(int num) {
    if (num < 0) {
        throw std::invalid_argument("Negative numbers are not allowed.");
    }
    std::cout << "Number: " << num << std::endl;
}

int main() {
    try {
        printNumber(-8);
    } catch (const std::invalid_argument& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }
}



/*
run:

ERROR!
Error: Negative numbers are not allowed.

*/

 



answered May 20, 2025 by avibootz
edited May 20, 2025 by avibootz
0 votes
#include <iostream>

bool isValidInput(int num) {
    return num >= 0; 
}

int main() {
    int num;
    std::cout << "Enter a number: ";
    std::cin >> num;

    if (!isValidInput(num)) {
        std::cerr << "Invalid input: Negative numbers are not allowed." << std::endl;
    } else {
        std::cout << "Valid input: " << num << std::endl;
    }
}



/*
run:

Enter a number: -9
Invalid input: Negative numbers are not allowed.

*/

 



answered May 20, 2025 by avibootz
0 votes
#include <cassert>

void printNumber(int num) {
    assert(num >= 0 && "Number must be non-negative");
    // Write your code here...
}

int main() {
    printNumber(-4); // This will terminate the program in debug mode
}




/*
run:

Enter a number: -9
main.cpp:4: void printNumber(int): Assertion `num >= 0 && "Number must be non-negative"' failed.
Aborted

*/

 



answered May 20, 2025 by avibootz
0 votes
#include <iostream>
#include <optional>

std::optional<int> safeCalculation(int num) {
    if (num < 0) return std::nullopt;
    return num * 2; // Calculation
}

int main() {
    auto result = safeCalculation(-6);
    
    if (result) {
        std::cout << "Result: " << *result << std::endl;
    } else {
        std::cout << "Invalid argument detected." << std::endl;
    }
}




/*
run:

Invalid argument detected.

*/

 



answered May 20, 2025 by avibootz

Related questions

1 answer 75 views
75 views asked May 20, 2025 by avibootz
4 answers 218 views
4 answers 241 views
4 answers 195 views
4 answers 200 views
3 answers 176 views
...