Tag: exception

在C#中转换exception

尝试执行此操作时为什么会出现InvalidCastException ? throw (ArgumentNullException)(new Exception(“errormessage”, null)); 这是以下function的简化版本。 public static void Require(bool assertion, string message, Exception innerException) where T: Exception { if (!assertion) { throw (T)(new Exception(message, innerException)); } } 完整的错误消息是: System.InvalidCastException:无法将类型为’System.Exception’的对象强制转换为’System.ArgumentNullException’。

从catch块中抛出嵌套的exception……这是明智的吗?

我想在我的库中实现自定义exception处理,以便我知道exception发生的位置,所以我这样做: try { DoSomething(); } catch(Exception ex) { //LibraryException refers to any exception in the libraries exception hierarchy throw new LibraryException(ex.Message, ex); } 这应该避免吗? 它有任何性能影响吗? 捕获,嵌套和重新抛出exception有什么含义?

DataContext.CreateDatabase()表示文件已经存在 – 但事实并非如此

这可能是Windows 7问题,但是调用 using (var context = new DataClassesDataContext()) { if (!context.DatabaseExists()) { context.CreateDatabase(); } } 导致以下错误: System.Data.SqlClient.SqlException未处理Message = Database’C:\ Temp \ SmallBusinessManager.mdf’已存在。 选择其他数据库名称。 Source = .Net SqlClient Data Provider ErrorCode = -2146232060 Class = 16 LineNumber = 1 Number = 1801 Procedure =“” Server = \。\ pipe \ 952FCA9D-B4B6-4C \ tsql \ query State = […]

来自OdbcConnection.Open()的奇怪exception

在这里抨击我们的头撞墙 我们是ISV,有数百家公司使用我们的软件没有任何问题。 该软件是.NET 2.0上的Winforms / C#。 我们的一个客户安装了我们的软件,它在所有机器的启动时崩溃,除了一个人的笔记本电脑,它工作正常。 在调用OdbcConnection.Open()时,我们得到以下exception: The type initializer for ‘System.Transactions.Diagnostics.DiagnosticTrace’ threw an exception. at System.Transactions.Diagnostics.DiagnosticTrace.get_Verbose() at System.Transactions.Transaction.get_Current() at System.Data.Common.ADP.IsSysTxEqualSysEsTransaction() at System.Data.Common.ADP.NeedManualEnlistment() at System.Data.Odbc.OdbcConnection.Open() at OurCompany.OurForm.connectionTestWorker_DoWork(Object sender) 这有一个InnerException: Configuration system failed to initialize at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey) at System.Configuration.ClientConfigurationSystem.PrepareClientConfigSystem(String sectionName) at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName) at System.Configuration.ConfigurationManager.GetSection(String sectionName) at System.Configuration.PrivilegedConfigurationManager.GetSection(String sectionName) at System.Diagnostics.DiagnosticsConfiguration.GetConfigSection() 谷歌只是说“app.config在语法上是不正确的,重建它”,但同样的app.config在数百台其他机器上运行正常。 这是app.config,根据要求: http://ourdomain.com/OurService.asmx […]

扩展方法的ArgumentNullException或NullReferenceException?

在null实例(扩展方法不允许)的情况下调用扩展方法时,您认为最好的exception类型是什么? 由于扩展方法只是静态方法,你可以说它应该是ArgumentNullException,但另一方面它们像实例方法一样使用,因此使用NullReferenceException可能更自然。 我们来看下面的例子: public static string ToInvariantString(this IFormattable value, string format) { return value.ToString(format, CultureInfo.InvariantCulture); } 这样,如果value参数为null,则抛出NullReferenceException。 另一个例子是: public static string ToInvariantString(this IFormattable value, string format) { if (value == null) throw new ArgumentNullException(“value”); return value.ToString(format, CultureInfo.InvariantCulture); } 编辑:在一些答案中,你已经指出扩展方法可以像静态方法一样调用,在这种情况下,空引用exception会出错,这是一个很好的观点,实际上是我关注的一个问题,不知道为什么我首先忘记在问题中提到这一点。 有人还指出抛出NullReferenceException是错误的,是的,确实如此。 这就是为什么我不扔它,我只是让它发生(让CLR抛出它)不守护方法。 我认为我赞成ArgumentNullException(这是我到目前为止所使用的)但我仍然认为至少有空间来反对NullReferenceException,因为在大多数将要使用该方法的地方看起来更自然。

如何定义已检查整数的列表

我有一个整数列表定义为List myIntList = new List(); 像往常一样,我将使用myIntList.Add()方法为列表添加值。 我面临的问题是列表中的值是动态的(一些计算的结果),可能超过整数可以容纳的最大值。 请考虑以下情形: int x = int.MaxValue; myIntList.Add(x + 1); 这将在列表中添加-2147483648而不是抛出exception。 我需要在这里抛出exception。 我知道myIntList.Add(checked(x + 1)); 将完美地完成工作,或者我甚至可以将myIntList.Add()括在checked{} ,如下所示: checked { myIntList.Add(12); myIntList.Add(int.MaxValue); myIntList.Add(x + 1); } 这是我的问题这有什么替代方案吗? 我可以定义已检查整数的列表吗? 如何在列表中添加的值超出限制的情况下创建引发exception的列表? 更新: 谢谢大家的回复,大多数人建议在将它们添加到列表之前检查整数(如果它超出边界则抛出exception)。 这与我通过给定的片段checked{// add elements }所做的相同,它将抛出exception而不进行任何复杂的条件检查。

如何正确捕获WinForms应用程序中的所有未处理的exception

我想为我的WinForms应用程序中的任何线程设置所有未处理exception的处理程序方法。 我自己不创建任何应用程序域。 根据UnhandledException文档,我需要通过Application.SetUnhandledExceptionMode方法设置UnhandledExceptionMode.ThrowException模式来捕获主线程的exception: 在使用Windows窗体的应用程序中,主应用程序线程中的未处理exception会导致引发Application.ThreadException事件。 如果处理此事件,则默认行为是未处理的exception不会终止应用程序,尽管应用程序处于未知状态。 在这种情况下,不会引发UnhandledException事件。 可以通过使用应用程序配置文件或使用Application.SetUnhandledExceptionMode方法在连接ThreadException事件处理程序之前将模式更改为UnhandledExceptionMode.ThrowException来更改此行为。 这仅适用于主应用程序线程。 针对在其他线程中引发的未处理exception引发UnhandledException事件 因此,生成的代码如下所示: public static void UnhandledExceptionEventHandler(object sender, UnhandledExceptionEventArgs e) { // … } [STAThread] static void Main(string[] args) { Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionEventHandler); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm(pathToCheck)); } 可以吗? 它会从任何线程(包括主线程,UI线程和Task类创建的所有线程)中捕获所有未处理的exception吗? 我是否正确理解了文档? 是的,我在这里看到了这样的问题,但我不明白我为什么还要使用以下代码: Application.ThreadException += new ThreadExceptionEventHandler(ErrorHandlerForm.Form1_UIThreadException);

流畅的NHibernateexception在集合之间移动对象

将一个对象从一个集合移动到另一个集合时,当cascade设置为all-delete-orphan时,我得到以下exception: 已删除的对象将通过级联重新保存(从关联中删除已删除的对象) 我认为当你使用all-delete-orphan时,nhibernate不会在另一个集合中引用它时删除它。 任何人都可以确认,当你有像文件夹这样的对象包含文件夹或文件并将文件从一个文件夹移动到另一个文件夹时,你不应该得到这个例外吗? 我在vs2010中制作了一个示例项目来演示这种行为。 任何人都可以说我的映射是正确的还是nhibernate中有错误? FileMapping.cs public class FileMapping: ClassMap { public FileMapping() { Id(x => x.Id, “Id”).GeneratedBy.Native(“File_seq”); Map(x => x.Name, “Name”).Not.Nullable(); References(x => x.Folder).Not.Nullable().Column(“idFolder”); } } FolderMapping.cs public class FolderMapping: ClassMap { public FolderMapping() { Id(x => x.Id, “Id”).GeneratedBy.Native(“Folder_seq”); Map(x => x.Name, “Name”).Not.Nullable(); HasMany(x => x.Folders).Inverse().Cascade.AllDeleteOrphan().KeyColumn(“idParentFolder”); HasMany(x => x.Files).Inverse().Cascade.AllDeleteOrphan().KeyColumn(“idFolder”); References(x => x.ParentFolder).Nullable().Column(“idParentFolder”); } […]

使用网络/文件系统调用时防止exception(预防性维护)?

我有一个朋友在这方面与我意见不一致,我只想在这种情况下得到一些关于谁是对错的反馈。 FileInfo file = …; if (file.Exists) { //File somehow gets deleted //Attempt to do stuff with file… } 我的朋友指出的问题是,“那么当我检查存在时文件是否存在怎么办?没有什么可以防止在检查文件被删除后尝试访问它会导致exception的可能性。所以,是否值得在前检查存在?“ 我能想到的唯一一件事就是MSDN清楚地检查了他们的例子,所以必须有更多。 MSDN – FileInfo 。 但是,它确实让我感到疑惑……额外的电话甚至值得吗?

溢出exception正在抛出 – 即使该值超出限制

为什么以下代码将输出设为-2而不是抛出overflow exception ? long x = long.MaxValue; long y = long.MaxValue + x;