0

<C++>In exception handling, do you need to know what exception and where an exception is going to occur? Can you make a code which will print and notify us that an exception occurred somewhere in the program. I mean I have a program in which I don't know if an exception will occur or not, if one was to occur, then it will print to notify us.

  • Could you provide some more details, please? Like a code snippet in which you want to check for exceptions. Generally, you can catch exceptions in C++ with `try` and `catch` but it really depends on your code how to best apply it. – user2393256 Oct 19 '21 at 11:17
  • 1
    Do you *need* to? Strictly speaking, no. It is possible to `catch` any exception that is thrown, but that's a last resort. If you have code where exceptions can be thrown, you should know what exceptions can be thrown. You could then either mitigate the possibility of them being thrown, or at least catch the specific exceptions and provide more meaningful diagnostics to your team. – sweenish Oct 19 '21 at 11:20
  • Yeah, but if I don't know what exception is going to occur, then what argument should I give in the throw part? – Programmer_2147483647 Oct 19 '21 at 12:01

2 Answers2

3

Exception handling is something you should design for, and in fact it works very well together with RAII (https://en.cppreference.com/w/cpp/language/raii). (Notr On embedded platforms using exceptions, is not so popular because of some runtime overhead). What I personally like about exceptions is that it separates error handling from the normal program flow (there will be hardly any if then else checks when done right)

// Exception handling should be part of your overal design.And many standard library functions can throw exceptions, It is always up to you where you handle them.

#include <iostream>
#include <string>
#include <stdexcept>

int get_int_with_local_exception_handling()
{
    do
    {
        try
        {
            std::cout << "Input an integer (local exception handling, enter a text for exception): ";
            std::string input;
            std::cin >> input;

            // stoi is a function that can throw exceptions
            // look at the documentation https://en.cppreference.com/w/cpp/string/basic_string/stol
            // and look for exceptions. 
            // 
            int value = std::stoi(input);

            // if input was ok, no exception was thrown so we can return the value to the client.
            return value;
        }
        // catch by const reference, it avoids copies of the exception
        // and makes sure you cannot change the content
        catch (const std::invalid_argument& e)
        {
            // std::exceptions always have a what function with readable info
            std::cout << "handling std::invalid_argument, " << e.what() << "\n";
        }
        catch (const std::out_of_range& e)
        {
            std::cout << "handling std::out_of_range, " << e.what() << "\n";
        }
    } while (true);
}

int get_int_no_exception_handling()
{
    std::cout << "Input an integer (without exception handling, enter a text for exception): ";
    std::string input;
    std::cin >> input;

    int value = std::stoi(input);
    return value;
}


int main()
{
    try
    {
        // this function shows you can handle exceptions locally
        // to keep program running
        auto value1 = get_int_with_local_exception_handling();
        std::cout << "your for input was : " << value1 << "\n";

        // this function shows that exceptions can be thrown without
        // catching, but then the end up on the next exception handler
        // on the stack, which in this case is the one in main
        auto value2 = get_int_no_exception_handling();
        std::cout << "your input was : " << value1 << "\n";

        return 0;
    }
    catch (const std::exception& e)
    {
        std::cout << "Unhandled exception caught, program terminating : " << e.what() << "\n";
        return -1;
    }
    catch (...)
    {
        std::cout << "Unknown, and unhandled exception caught, program terminating\n";
    }
}
Pepijn Kramer
  • 9,356
  • 2
  • 8
  • 19
  • in your example you know what exceptions might be thrown, but OP asks how to handle unknown exceptions. I'd expect `catch(...)` to be mentioned – 463035818_is_not_an_ai Oct 19 '21 at 11:42
  • Added, this still leaves ofcourse the real bad ones, like memory access violations which still won't be caught at all. Here the memory dump analysis approaches come into play. – Pepijn Kramer Oct 19 '21 at 11:47
  • good point. Often c++ exceptions are confused with excpetions coming from somewhere deep down – 463035818_is_not_an_ai Oct 19 '21 at 11:48
  • yes C++ exceptions should be used for handling expected exceptions and can be designed for, the other exceptions (like access violations) are usually programming bugs anyway (and should indeed lead to crashes, the sooner the better since the program is in an indeterminate state anyway) – Pepijn Kramer Oct 19 '21 at 11:54
1

Yes and no.

No, because any exception thrown via throw some_exception; can be catched via catch(...).

Yes, because catch(...) is not very useful. You only know that there was an excpetion but not more.

Typically exceptions carry information on the cause that you want to use in the catch. Only as a last resort or when you need to make abolutely sure not to miss any excpetion you should use catch(...):

 try {
      might_throw_unknown_exceptions();
 } catch(std::exception& err) {
      std::cout << "there was a runtime error: " << err.what();
 } catch(...) {
      std::cout << "an unknown excpetion was thrown.";
 }

The C++ standard library uses inheritance only sparingly. Exceptions is only place where it is used extensively: All standard exceptions inherit from std::exception and it is good practice to inherit also custom exceptions from it.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185