Is it possible to throw two values at the same time?
I have 4-line and two throw statements ;
Pseudocode ;
In function f () 开发者_开发问答
if a == 2
throw SMT_0
if b == 3
throw SMT_1
For a != 2 and b != 3, I want to throw both throw statements, simultaneously. How can I do ?
ex :
if a!= 2 && b != 3
throw SMT_0 and SMT_1
You cannot. But you can throw any object, so you can use OO techniques to have the one object you throw contain the relevant information from both SMT_0
and SMT_1
.
What are the thrown values, and what does your catch
block look like?
Update:
OK, so it looks like you want to throw the reason(s) that your input was not correct.
Question: why? Is it that important that all of the reasons have to be reported? Maybe you can simply throw reporting one of the reasons, let the user fix that and iterate? (If the intended recipient of the information is not the user but instead the programmer, I see absolutely no reason that all of the errors have to be reported at once).
Now, if you do have to throw reporting all errors, then you can simply throw an array of enum CLASSNAME.REASONS
instead of one value.
it smells like you are trying to control program flow with exceptions... not a good idea.
but since you ask, why don't you just have a third alternative throw SMT_01 ?
You may wish to consider using boost exceptions. This will give you a way to introduce tagging into your exception hierarchy. That is, you may have a single exception that carries many bits of information.
For example (something I do), if you have a parser any syntax error you get has multiple things to propagate. First off, you'll create the exception with the exact error you've encountered, like a syntax error. In a function higher on the stack you can catch this exception add line and file information.
At creation time you are also free to add many tidbits of information at the same time. Say you derive a boost exception called my_error
. You can also define the tags you want so your examples might look like this:
if( a != 2 && b != 3 )
throw my_error() << SMT_0 << SMT_1
if( a == 2 )
throw my_error() << SMT_0
if( b == 3 )
throw my_error() << SMT_1
If you have an enum, as you indicate in a comment, you might want to a tag that simply takes that enum as a param, though you may only use each tag once in the exception.
精彩评论