Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6570401
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T14:45:07+00:00 2026-05-25T14:45:07+00:00

I’m working in some code that uses exceptions a lot to handle certain error

  • 0

I’m working in some code that uses exceptions a lot to handle certain error conditions (certainly not the best design by any means, but it’s what I’m working with).

When an exception occurs in code, I need an elegant way of cleaning up any open or temporary resources.

This can be performed like this:

try
{
    foo();
    bar();
}
catch (Exception)
{
    // Oops, an error occurred - let's clean up resources
    // Any attempt to cleanup non-existent resources will throw
    // an exception, so let's wrap this in another try block
    try
    {
        cleanupResourceFoo();
        cleanupResourceBar();
    }
    catch
    {
        // A resource didn't exist - this is non-fatal so let's drop
        // this exception
    }
}

Let’s say that the foo() method cleaned up after itself properly, but the bar() method threw an exception. In the cleanup code, we will call cleanupResourceFoo() first which itself will throw an exception as the foo resources have already been cleaned up.

This means that cleanupResourceBar() won’t end up being called and we’ll end up with a resource leak.

Of course we could re-write the inner try/catch block like so:

try
{
    cleanupResourceFoo();
}
catch
{
}
try
{
    cleanupResourceBar();
}
catch
{
}

but now we’re getting pretty ugly.

I come from a C++ background and this is the kind of thing I would normally use RAII for. Any recommendations about an elegant way to handle this in C#?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T14:45:07+00:00Added an answer on May 25, 2026 at 2:45 pm

    Cleaning up resources should almost always be handled via using statements and IDisposable – so you’d simply have:

    using (FirstResource r1 = ...)
    {
        using (SecondResource r2 = ...)
        {
            ...
        }
    }
    

    If you only want to clean up resources on exception, that’s somewhat rarer – and not something I’d expect RAII to particularly help you with in C++. You could potentially use delegates to make this simpler:

    TryWithCleanUpOnException(foo, cleanUpResourceFoo);
    TryWithCleanUpOnException(bar, cleanUpResourceBar);
    
    ...
    
    private static void TryWithCleanUpOnException(Action action,
                                                  Action cleanUp)
    {
        bool success = false;
        try
        {
            action();
            success = true;
        }
        finally
        {
            if (!success)
            {
                cleanup();
            }
        }
    }
    

    By not catching the exception, this allows errors to propagate rather than being swallowed. This is normally what you want – if it isn’t in your case, perhaps you could explain more precisely what your situation is.

    You’ve said that there are non-fatal exceptions that you effectively want to ignore – but you generally shouldn’t just catch Exception and keep going: catch specific exceptions that you expect in particular situations. Obviously you may have a very special situation, but this is general advice which holds most of the time. You can restructure the helper method above to catch exception if you really want.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I need a function that will clean a strings' special characters. I do NOT
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but
For some reason, after submitting a string like this Jack’s Spindle from a text
I've got a string that has curly quotes in it. I'd like to replace
I have a French site that I want to parse, but am running into
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.