我有类似于以下的代码:
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/