chris1992
chris1992

Reputation: 51

C++ Exception handling without try

I am currently trying to write a function for a specific type of hardware exception handling.

The program should test, whether a certain condition is true and start a short emergency procedure and finally terminate.

This test will have to be done quite often and should be rather quick.

Further, it is implemented in a project without any further exception handling.

Therefore, putting try statements everywhere is not really an option.

Ideally, such a function would look like this:

void CheckForException(){
  if (Condition == true){
    cout << "The chosen configuration is very dangerous, do something different!" << endl;

    someHardwareFunction();

    someStatementEndingTheProgram;
  }
}

In principle, I am looking for someStatementEndingTheProgram.

I figured, end(), terminate() and the like are bad style.

Could a throw statement without a try work in this case?

Upvotes: 0

Views: 4946

Answers (2)

slashmais
slashmais

Reputation: 7155

This reeks of bad design in your app.

If you want to prevent the overhead of try-catch but still handle exceptions/error-conditions in a robust way, the code must cater for it: in effect replacing the exception-handling with a custom optimized handler.

In your example you have two basic choices:

  1. if the someStatementEndingTheProgram needs to do cleanup you can call exit() at the exit-point of that function, otherwise just replace it with exit().

  2. redesign your app to handle CheckForException() returning a status, and check that status higher-up the call-chain, e.g.:

int main()
{
    bool okay=true;
    while (okay) 
    {
        okay=CheckForException();
        //other code
    }
    if (okay) return 0; else return ERROR_CODE;
}

which will let your app terminate normally.

Upvotes: 0

stefaanv
stefaanv

Reputation: 14392

Not answering the title, but the actual problem description: even if putting try's everywhere is not an option, you can wrap the complete code of the main() function in a try block and catch std::exception, so when CheckForException will throw, it will be caught there, so displaying a message and exiting the application can be done easily.

The downside to this approach is that there can be try blocks in your program later on that could catch this exception, so it should be rethrown.

Upvotes: 1

Related Questions