Home > Net >  Do you need to know what exception is going to occur to handle them in C ?
Do you need to know what exception is going to occur to handle them in C ?

Time:10-19

<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.

CodePudding user response:

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";
    }
}

CodePudding user response:

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.

CodePudding user response:

(this is quite a Windows specific answer)

if one was to occur, then it will print to notify us

If your program has crashed due to an exception, the program is in a state where it cannot guarantee that anything works. "Printing" (like std::cout) might not even work any more. If you accidentally close the program, the message is gone.

Also: Having a printed statement does typically not help you that much. You want to look at call stacks, memory, exception codes etc. It would need to be a very long print statement.

I suggest you have a look at creating memory dumps with WER LocalDumps. It will save the whole program's state when it crashed and you have all information like CPU times, threads, call stacks and even access to memory.

Become familiar with debugging in crash dumps. It's very useful.

At the same time, read about PDBs and how to store them so they are useful.

  • Related