0
我試圖在代碼中捕捉到「嵌套」或「封裝」自定義錯誤(I504Error
)。我知道這通常不是最佳實踐,但它應該適用於我的用例,因爲錯誤非常具體。我試圖讓try/catch
區塊在我的Main
方法中捕獲I504Error
,但它無法捕獲它,即使它是從try/catch
區塊內部調用的。我的程序停止在我拋出錯誤的地方。我在這裏做錯了什麼?C#不會捕獲「嵌套」自定義異常
// Custom Error Handler
public class I504Error : Exception
{
public I504Error()
{
}
}
// Classes
public abstract class AbstractIternetThing
{
public abstract void DoSomething();
}
public class IternetThing : AbstractIternetThing
{
public override void DoSomething()
{
// bunch of other stuff
if (iternetThingWorkedProperly == false)
{
// Program stops here, doesn't get caught by the try/catch block in Program.Main()
throw new I504Error();
}
}
}
// Main script
class Pogram
{
static void Main(string[] args)
{
List<Task<AbstractIternetThing>> programThreads = new List<Task<AbstractIternetThing>>();
IternetThing iThing = new IternetThing();
try
{
for (int wantedThread = 0; wantedThread < 5; wantedThread++)
{
Task<AbstractIternetThing> iThingTask = new Task<AbstractIternetThing>(() => iThing.DoSomething());
iThingTask.Start();
}
}
// The Error should get caught here, but it doesnt?
catch (I504Error)
{
// Do something else
}
}
}