is it wrong to use try and catch for output ?

I only know that try and catch are best used in I/O operation. I don't really use them.

so I got some idea

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
try {
    if( some_condition ) throw Verdict::ERROR_1;
    
    // some other code
    
    throw Verdict::OK;
}
catch( Verdict& v ){
    switch( v ){
    case Verdict::ERROR_1:
       // error handling 
    break;
    case Verdict::OK:
       // do the real work here
    break;
    }    
}


so I use it like this code inside try is for validation and code in catch is for error handling and the real output.
Is this using feature that aren't meant to be used this way ?

Code::Blocks Debugger stops every time it reaches throw which happens every time this piece of code is called because whatever happens it always throws.
I want the solution to that too if possible.
Is this using feature that aren't meant to be used this way ?
Yes. Exceptions are not intended to be used for input checking and flow control. They are "Oh, crap, we are doomed" situations where you cannot handle problem on-site and need to delegate it to the caller.

Generally throwing exception in try block and catching it immediatly in corresponding catch block is smells very bad. Use simple if statements in your case.
> is it wrong to use try and catch for output ?

No, there are situations where you would want to use exceptions for i/o errors.
See: std::basic_ios::exceptions() http://en.cppreference.com/w/cpp/io/basic_ios/exceptions


isocpp FAQ has a good section on 'Exceptions and Error Handling'. Excerpt:
What shouldn’t I use exceptions for?

C++ exceptions are designed to support error handling.

Use throw only to signal an error (which means specifically that the function couldn’t do what it advertised, and establish its postconditions).

Use catch only to specify error handling actions when you know you can handle an error (possibly by translating it to another type and rethrowing an exception of that type, such as catching a bad_alloc and rethrowing a no_space_for_file_buffers).

Do not use throw to indicate a coding error in usage of a function. Use assert or other mechanism to either send the process into a debugger or to crash the process and collect the crash dump for the developer to debug.

Do not use throw if you discover unexpected violation of an invariant of your component, use assert or other mechanism to terminate the program. Throwing an exception will not cure memory corruption and may lead to further corruption of important user data.

...

In particular, do not use exceptions for control flow.


You might want to read the whole section: https://isocpp.org/wiki/faq/exceptions
Thanks for the reply. I am sorry I am late to reply. I will perhaps use goto instead ? because I really want to separate the checking and the action taken but without using function.
Topic archived. No new replies allowed.