【问题标题】:How to Stop Catching a Specific Exception in C#如何在 C# 中停止捕获特定异常
【发布时间】:2013-12-02 05:07:45
【问题描述】:

问题

我正在为标签(100..标签)分配一些字符串值(所有值都不同)

例子:

Label1.Text=Excel.Worksheet1.Cells[1,1];
Label2.Text=Excel.Worksheet1.Cells[1,2];
Label3.Text=Excel.Worksheet1.Cells[1,3];
Label4.Text=Excel.Worksheet1.Cells[1,4];
........
........
........
Label100.Text=Excel.Worksheet1.Cells[1,5];

在为标签分配一些值时.. 一些 Excel 单元格值可能为空.. 它捕获异常(例如 NULL 值异常)。在这种情况下,我希望 不要捕获任何指定的异常。

它应该继续执行而不捕获给定的异常(空异常)。

  • 这里我不能对所有代码行使用try {..} catch {..}..
  • 程序执行不应跳转/错过任何代码行..

如何解决这个问题?

【问题讨论】:

  • 为什么不直接使用 if-else 语句来检查 null?
  • Text 分配给null 不应该抛出异常,实际问题是什么?
  • 使用默认的 catch 和 if 语句检查类型,但你的错误检查应该比 if any is throwed run this logic...
  • 什么会引发异常 - Label#.Text 设置器或 Excel.Worksheet.Cells 索引器?
  • @GarethCornish 可能是后者。 Setter 通常不会抛出异常。

标签: c# exception


【解决方案1】:

您是否可以为每个单元格的值为null 的情况提供一个条件,并使用空字符串"" 作为labelX.txt 来代替?当您将标签值分配给 null 时,这听起来像是抛出异常。

例子:

if(Excel.Worksheet1.Cells[1,1] != null{
    Label1.Text = Excel.Worksheet1.Cells[1,1]
}
else{
    Label1.Text = ""
}...

【讨论】:

    【解决方案2】:

    如果 Label1.Text 设置器抛出错误,您可以尝试 ?? 构造:

    Label1.Text = Excel.Worksheet1.Cells[1,1] ?? string.Empty;
    

    这会将值设置为Excel.Worksheet1.Cells[1,1](如果不为空),如果为空则设置为string.Empty

    如果错误是由Excel.Worksheet1.Cells[1,1] 索引器引发的,您需要编写一个方法来包含您的设置逻辑:

    // Assuming the Excel object is global and static; otherwise you'll need to 
    // include a reference to that too
    private string GetExcelWorksheetValue(int index1, int index2){
        try{
            return Excel.Worksheet1.Cells[index1, index2];
        } catch(NullReferenceException err){ // Or whatever type of Exception you're trying to catch
            return string.Empty;
        }
    }
    

    然后将流程中的每一行更改为:

    Label4.Text = GetExcelWorksheetValue(1,4);
    

    【讨论】:

    • 但是 OP 不是明确尝试 not 来捕获 NullReferenceExceptions 吗?
    • 不可能阻止任何类型的异常在不捕获和处理的情况下中断进程。我从这个问题中了解到,OP 正试图通过破坏他的代码来防止不得不处理异常。
    【解决方案3】:

    为了停止空异常,我使用了以下技术。

    Label1.Text=(Excel.Worksheet1.Cells[1,1].value ?? "Some_Str";
    Label2.Text=(Excel.Worksheet1.Cells[1,2].value ?? "Some_Str";
    Label3.Text=(Excel.Worksheet1.Cells[1,3].value ?? "Some_Str";
    Label4.Text=(Excel.Worksheet1.Cells[1,4].value ?? "Some_Str";
    

    如果 excel 有一些空字段,它会被其他字符串重新获取

    如果为 null 则 Some_Str 否则它的值。 很简单。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-28
      • 2021-12-17
      • 2010-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多