简体   繁体   中英

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.

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. 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.

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.

Side note: it's generally a bad practice to do catch (Exception) to catch any 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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