c# - How to associate a customized number with exception -
i have code want throw 2 exceptions; however, exception same different values. know elegant generic way determine of these errors occurred.
i know can 2 try catches or can set boolean determine success of query. aware can done in 1 query; however, need able determine if company key wrong or if pa id wrong. know can create own exception , add additional field it. unfortunately, not believe of these optimal solution , has been bothering me quite time.
any information best practice appreciated.
using (var ora = new oracleconnection(data.connectionstring)) { string sqlgetcompanyid = "select company_id companies key = :key"; string sqlvalidatedelete = "select * pa pa_id = :paid , company_id = :cid"; ora.open(); int companyid = 0; using (var command = ora.createcommand()) { command.commandtext = sqlgetcompanyid; command.parameters.add(":key", oracledbtype.varchar2).value = ckey; using (var reader = command.executereader(commandbehavior.singlerow)) { if (reader.read()) companyid = unchecked((int)((long)reader["company_id"])); else throw new argumentexception("invalid company key"); } } using (var command = ora.createcommand()) { command.commandtext = sqlvalidatedelete; command.parameters.add(":cid", oracledbtype.int32).value = companyid; command.parameters.add(":paid", oracledbtype.int32).value = paid; using (var reader = command.executereader(commandbehavior.singlerow)) { if (!reader.read()) throw new argumentexception("price agreement id company not exist"); rv = unchecked((int)((long)reader["row_version"])); } } }
i'd suggest creating custom exception each:
public class invalidcompanykeyexception : argumentexception { public invalidcompanykeyexception() : base() {} public invalidcompanykeyexception(string message) : base(message) {} public invalidcompanykeyexception(string message, exception inner) : base(message, inner) {} } public class priceagreementidnotfoundexception : argumentexception { public priceagreementidnotfoundexception() : base() {} public priceagreementidnotfoundexception(string message) : base(message) {} public priceagreementidnotfoundexception(string message, exception inner) : base(message, inner) {} }
you can catch these separately, or can catch either 1 argumentexception
. i've included 3 separate constructors each exception because that's microsoft recommends. recommend making exception serializable if they'll used in scenarios, example doesn't seem require serialization.
Comments
Post a Comment