Search code examples
mysqlexceptionerror-handlingusing-statementtry-catch-finally

Do I need to release a connection if I throw an error?


So if I get a connection pool, then something unexpected happens and the error will be thrown, do I need to additionally release a connection? What happens with the MySQL connection pool once the error is thrown?


Solution

  • You didn't tell us what programming language you use, or what sort of exception you want to catch. So it's hard to be specific.

    In general, the answer is yes. Always release / dispose / deallocate any resources like connections and cursors. These sorts of resources are sometimes called serially reusable resources. If you don't release them they'll eventually become used up and your program will stop working. If you're lucky it will crash. If you're unlucky it will just hang waiting for a resource that will never arrive.

    Some languages use the try {} catch() {} finally {} pattern to release resources whenever allocated. Put your connection release code in the finally{} block, and it will always run.

    C# uses using (var resource = getSomeResource()) {}. This pattern ensures the resource's .dispose() method is always invoked even if the code in the block throws an exception.

    The more care you take with this, the longer your program will run without crashing due to some kind of resource leak. The language constructs I mentioned were invented precisely to solve your problem robustly.