To Throw or To Return (Exceptions vs Result Object)?

To throw or return (Exceptions vs Result Object)

Leave a Reply

Comment as a guest.

  1. Great article and definitely not easy topic, thank you for summing this up 🙂

    In your example with `LoadFileData` it’s questionable whether exception should be thrown if file does not exist. I would say it depends. If I’m blindly reading files from drive then non-existing file seems to be somewhat expectable.

    I wrote simple benchmakrs using custom readonly struct result type (having only `Value` and `Error` property) and I see different numbers. Could you check what overhead does `Result.Net` add? Has anything changed in .NET 6? For me, both success and failure with Result type are 5x times faster than success without exception, and both success and failure using result type are identical.

    Last but not least allow me to add additional comments to pros of using exceptions:

    – Clean and descriptive: but only if you document it! Otherwise caller may have no clue about your method throwing. (I wish it was part of signature like in Java).

    – Easy to use: easy to throw, headache to handle exceptions properly in the right place ¯\_(ツ)_/¯

    1. Thanks for your comment,
      regarding the “LoadFileData” function, in the example that I give, we expect the function to execute without any failures, and yes as you said, “If I’m blindly reading files from drive then non-existing file seems to be somewhat expectable.” you’re right but in our example, we have limited the function to only read the file content. so if the file for example doesn’t exist it should be controlled by the one who is calling this function.
      I re-run the same benchmarks on .NET 6.0.2, for the 1000 items iteration and the results are deferents, there is a gain of X2 in performance.

Read Next

Sliding Sidebar