Why doesn't try {} catch{} work in C#?

2019-09-11 03:00发布

问题:

I have a try{} catch{} block in my program in Visual Studio. In the try{} block I have code to connect to a DB and when I run that program it returns an error. In this situation the program must execute the catch{} block, but an error is returned from the try{} block and the program stops.

try {
  using (OracleConnection cn = new OracleConnection(DataBase.EDS_SDE_Connection)) {
    cn.Open();
    using (OracleCommand cm = cn.CreateCommand()) {
      cm.CommandType = CommandType.StoredProcedure;
      cm.CommandText = "EDS_FEAUTRE_CLASSES.DIS_ENA_TRG_LOG";
      OracleParameter oParam = new OracleParameter("PISDISABLE", OracleDbType.Decimal);
      oParam.Direction = ParameterDirection.Input;
      oParam.Value = pIsDisable;
      cm.Parameters.Add(oParam);
      cm.ExecuteNonQuery();
    }
  }
  bRet = true;
} catch (Exception ex) {
  ClsShares.ShowMessage("", ex.Message);
  bRet = false;
}

That's was from bellow highlighted chekbox:

回答1:

Not all exception types are enabled to break the solution by default. You can choose which are enabled from the Exception Setting window as you show above in the image. Set the CLR exceptions set to be thrown. That's how the code will break (if there is no a try/catch) or in your case the try sequence will break and the catch block will be executed.

For different IDEs:

VS2015: Debug -> Windows -> Exception Settings.

VS2012: Debug -> Exceptions more details