简体   繁体   English

C#在调用堆栈中捕获未处理的异常

[英]C# Catch Unhandled Exception Down the Call Stack

I have a program that goes numerous functions deep to load a file and the chance for error in any of those functions is possible due to the possibility of loading a corrupted file. 我有一个程序,该程序具有许多功能,可以深度加载文件,由于加载损坏的文件的可能性,这些功能中的任何一个都有可能出错。

I want to try catching any unhandled exception that's thrown while loading these files in the function that's calling the load function. 我想尝试捕获在调用load函数的函数中加载这些文件时引发的任何未处理的异常。

Is it possible to do this without putting a try catch in every single function called in the loading process? 是否可以在装入过程中调用的每个函数中都没有尝试捕获的情况下执行此操作?

try {
    var loadedFile = new LoadedFile(path);
    fileList.Add(loadedFile);
}
catch (Exception e) {
    Console.WriteLine("Error Loading File");
}

Yes its possible. 是的,它有可能。 Simply surround the top most function call with a try catch. 只需用try catch包围最上面的函数调用即可。 Any exceptions will be thrown all the way out. 任何异常都将被抛出。 However you should catch it in the function it occurs and, assuming you can, fix the cause of the exception inside that function. 但是,您应该在发生它的函数中捕获它,并且,如果可以的话,请修复该函数内部的异常原因。 If you can't you program must fail because it can not accomplish the task. 如果不能,则程序必须失败,因为它无法完成任务。

For example, if the file is corrupted the program should fail; 例如,如果文件损坏,则程序应失败; if the file has a lock on it from another process you can wait until the lock is released (assuming it is ever released) before continuing or otherwise fail out. 如果文件在另一个进程上对其具有锁定,则可以等待该锁定被释放(假设它曾经被释放),然后继续操作,否则失败。

Unhandled exceptions "bubble up" the call stack until they are caught, or the application throws an unhandled exception error. 未处理的异常会“阻塞”调用堆栈,直到捕获它们为止,否则应用程序将引发未处理的异常错误。 You can put a try...catch block in your higher-level function, and it will catch exceptions thrown at the lower levels. 您可以在较高级别的函数中放置一个try...catch块,它将捕获较低级别的异常。

For example: 例如:

public void CatchEmAll()
{
    try
    {
        DoSomethingExceptiony();
    }
    catch (Exception ex)
    {
        // handle the exception
    }
}

public void DoSomethingExceptiony()
{
    throw new Exception("Uh oh!");
}

In this case, the exception thrown in DoSomethingExceptiony is not caught at that level, but bubbles up to the calling function CatchEmAll , where it is caught. 在这种情况下,不会在该级别捕获在DoSomethingExceptiony引发的异常,但是会在捕获该异常的调用函数CatchEmAll

Side note: it's generally a bad practice to do catch (Exception) to catch any exception. 旁注: catch (Exception)来捕获任何异常通常是一种不好的做法。 It's better to understand what types of exceptions could be thrown by your code, and handle only those. 最好了解您的代码可能抛出什么类型的异常,并仅处理那些异常。 For example, if you are loading a file, you might catch FileNotFoundException specifically, but not any and all exceptions. 例如,如果要加载文件,则可以专门捕获FileNotFoundException ,但不能捕获任何异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM