c# - 异常不抛出?

标签 c# .net exception

我有类似于以下的代码:

try{
    func1();
}
catch(Exception e){
    /Do something
}


static func1(){
    func2();
}

static func2(){
    //Exception thrown here
    System.IO.StreamReader file = new System.IO.StreamReader(filePath);
}

当 func2() 中的代码行抛出异常时,我在 catch 子句中没有收到任何通知。我没有明确抛出任何东西,我只是有常规的静态函数声明——没有“抛出”出现在任何地方。

为什么异常没有向上传播到 catch 语句??

最佳答案

不,代码没问题。您的真实代码中有些内容没有向我们展示。该异常传播良好:

using System;

static class Program {
    static void Main() {
        try{
            func1();
        } catch(Exception e) {
            // works fine: FileNotFoundException
            Console.WriteLine(e);
        }
    }
    static void func1(){
        func2();
    }    
    static void func2() {
        string filePath = "doesnot.exist";
        System.IO.StreamReader file = new System.IO.StreamReader(filePath);
    }
}

候选人:

  • 任何涉及 try 的事情都是可疑的 - 三重检查
  • 任何涉及线程的事情都可能在其他地方出现异常

关于c# - 异常不抛出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10911369/

相关文章:

c# - oledb 导入 csv 文件 - 奇怪的字符 :˥«¿ added

c# - 从 Controller 实例化 IRepository 类的正确方法是什么?

c# - 通过 C# Azure 管理库将 SSL 绑定(bind)添加到 Azure 网站

c# - 从 DotNetNuke 中的 FileId 生成 URL

c# - 你将如何获得队列中的第一个和最后一个项目?

java - 必须为元素 "type"异常声明属性 "forward".. 它是关于什么的..?我们必须做出什么改变..?

C# Pragma 在抛出错误时抑制中断

c# - Application.ThreadException 事件未捕获绑定(bind)属性的 Set 方法中的异常

c# - app.UseRouting() 和 app.UseEndPoints() 有什么区别?

.net - 服务启动时的 DLL 加载顺序