The cost of throwing exceptions

You can become a serverless blackbelt. Enrol to my 4-week online workshop Production-Ready Serverless and gain hands-on experience building something from scratch using serverless technologies. At the end of the workshop, you should have a broader view of the challenges you will face as your serverless architecture matures and expands. You should also have a firm grasp on when serverless is a good fit for your system as well as common pitfalls you need to avoid. Sign up now and get 15% discount with the code yanprs15!

After reading Ayende‘s post today, it got me thinking, just exactly what’s the cost of a try/catch block and more importantly what’s the cost of throwing exceptions.

Like Ken Egozi mentioned in the comments, I too believe the test was unfair as the try/catch block was applied to the top level code as opposed to each iteration. However, based on everything I know about exception in .Net I’d imagine whatever performance cost will be associated with throwing the exceptions rather than simply trying to catch them. With that in mind, I decided to carry out my own set of tests to try out three simple cases:

  1. 10000 invocations of a blank Action delegate, this should be considered as the ‘base line’ of the cost of iterating through the integers 1 – 10000 and whatever cost of invoking a delegate

  2. 10000 invocations of a blank Action delegate INSIDE a try-catch block, this should indicate the additional cost of trying to catch an exception when compared with 1.

  3. 10000 invocations of an Action delegate that throws an exception INSIDE a try-catch block, this should indicate the additional cost of throwing and catching the exception when compared with 2.

Each test of 10000 invocations are repeated 100 times (no debugger attached) and here are the average execution times in milliseconds:

image

For anyone who wants to try it out themselves, I’ve posted the code on github here.

As you can see, wrapping a call inside a try-catch block doesn’t add any meaningful cost to how fast your code runs, although there’s a measurable difference when exceptions are repeatedly thrown but 300 milliseconds over 10k exceptions equates to over 30k exceptions per second, which dare I say is more than anyone would rationally expect from a real-world application!

Another thing to consider is the impact the stack trace depth has on the cost of throwing exceptions, to simulate that I put together a second test which executes a method recursively until it reaches the desired level of recursion then throws an exception. Each test performs this recursion 1000 times, and repeated over 100 times to get a more accurate reading. Here are the average execution times in milliseconds:

image

Good news is that the cost of going deeper before throwing an exception seems to be linear as opposed to exponentially.

Closing thoughts…

Before I go I must make it clear that exceptions are necessary and the ability to throw meaningful exceptions is a valuable tool for us developers in order to validate business rules and communicate any violations to the consumers of our code. As far as these performance tests go, they’re merely intended to make you aware that there IS a cost associated with throwing exception and not to mention a little bit of fun!

Ultimately, throwing exceptions means doing work, and doing work takes CPU cycles, so you really shouldn’t be surprised to see that there’s a cost for throwing exceptions. Personally, I take my exceptions seriously, for all the projects I have worked on I have taken the time to define a set of clear and meaningful exceptions, each with a unique error code ;-)

The question you gotta ask yourself is this – would you trade 0.03ms in exceptional cases for cleaner, more concise code that lets you communicate errors to users more clearly and help you debug/fix bugs much more easily? Knowing that you end up paying for it in terms of code maintenance, debugging time anyway, I sure as hell knows which one I’d prefer! Remember, avoid premature optimization, profile your application, target the real problems and then optimize instead.

Liked this article? Support me on Patreon and get direct help from me via a private Slack channel or 1-2-1 mentoring.
Subscribe to my newsletter


Hi, I’m Yan. I’m an AWS Serverless Hero and I help companies go faster for less by adopting serverless technologies successfully.

Are you struggling with serverless or need guidance on best practices? Do you want someone to review your architecture and help you avoid costly mistakes down the line? Whatever the case, I’m here to help.

Hire me.


Skill up your serverless game with this hands-on workshop.

My 4-week Production-Ready Serverless online workshop is back!

This course takes you through building a production-ready serverless web application from testing, deployment, security, all the way through to observability. The motivation for this course is to give you hands-on experience building something with serverless technologies while giving you a broader view of the challenges you will face as the architecture matures and expands.

We will start at the basics and give you a firm introduction to Lambda and all the relevant concepts and service features (including the latest announcements in 2020). And then gradually ramping up and cover a wide array of topics such as API security, testing strategies, CI/CD, secret management, and operational best practices for monitoring and troubleshooting.

If you enrol now you can also get 15% OFF with the promo code “yanprs15”.

Enrol now and SAVE 15%.


Check out my new podcast Real-World Serverless where I talk with engineers who are building amazing things with serverless technologies and discuss the real-world use cases and challenges they face. If you’re interested in what people are actually doing with serverless and what it’s really like to be working with serverless day-to-day, then this is the podcast for you.


Check out my new course, Learn you some Lambda best practice for great good! In this course, you will learn best practices for working with AWS Lambda in terms of performance, cost, security, scalability, resilience and observability. We will also cover latest features from re:Invent 2019 such as Provisioned Concurrency and Lambda Destinations. Enrol now and start learning!


Check out my video course, Complete Guide to AWS Step Functions. In this course, we’ll cover everything you need to know to use AWS Step Functions service effectively. There is something for everyone from beginners to more advanced users looking for design patterns and best practices. Enrol now and start learning!