Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can/Should you throw exceptions in a c# switch statement?

I have an insert query that returns an int. Based on that int I may wish to throw an exception. Is this appropriate to do within a switch statement?

 switch (result)
        {

            case D_USER_NOT_FOUND:
                throw new ClientException(string.Format("D User Name: {0} , was not found.", dTbx.Text));
            case C_USER_NOT_FOUND:
                throw new ClientException(string.Format("C User Name: {0} , was not found.", cTbx.Text));
            case D_USER_ALREADY_MAPPED:
                throw new ClientException(string.Format("D User Name: {0} , is already mapped.", dTbx.Text));
            case C_USER_ALREADY_MAPPED:
                throw new ClientException(string.Format("C User Name: {0} , is already mapped.", cTbx.Text));
            default:

                break;
        }

I normally add break statements to switches but they will not be hit. Is this a bad design? Please share any opinions/suggestions with me.

Thanks, ~ck in San Diego

like image 423
Hcabnettek Avatar asked Apr 22 '10 18:04

Hcabnettek


1 Answers

Why not?

From The C# Programming Language, Third Ed. by Anders Hejlsberg et al, page 362:

The statement list of a switch section typically ends in a break, goto case, or goto default statement, but any construct that renders the end point of the statement list unreachable is permitted. [...] Likewise, a throw or return statement always transfers control elsewhere and never reaches its end point. Thus the following example is valid:

switch(i) {
case 0:
    while(true) F();
case 1:
    throw new ArgumentException();
case 2:
    return;
}
like image 129
Daniel Pryden Avatar answered Oct 05 '22 09:10

Daniel Pryden