DEV Community

loading...

Discussion on: Custom exceptions with JS

Collapse
danielpdev profile image
danielpdev

Good article!
It's easy to just throw error and use catch to handle the exception, but ideally you shouldn't use throw very often as it's a huge drawback on performance.

Collapse
sqlrob profile image
Robert Myers

The way I've always heard, and continue to follow, exceptions are for exceptional conditions. They shouldn't be for logic flow.

In a good many of my projects (all languages), there's plenty of throws, but almost no catches at all, except maybe at or near the top level. In the case of errors, I want things to blow up. If the db goes down, there's not much I can do. If I have a bug that results in a throw, it's noisy and I have a nice stack trace right to it, fail early and noisy.

Collapse
damxipo profile image
Damian Cipolat Author

Well I'm using this way in a very massive production project and we don't lose Performance. Do you have a link that supports this or what you say or experience to tell?

Collapse
danielpdev profile image
danielpdev

try-catch will impact your performance only if you actually throw exceptions.
Examples:

  1. Performance loss when exception is thrown: jsperf.com/try-catch-performance-jls
  2. No performance loss if no exception is thrown: jsperf.com/try-catch-performance-j...

Conclusion:
I'm not saying that you should not use try-catch at all, but like in the examples above actually throwing an exception can be easily avoided.

Thread Thread
damxipo profile image
Damian Cipolat Author

Nice, thanks for the links provides very useful information. I will be investigating about this.

Collapse
renatoruk profile image
Renato Ruk

Can you explain this in more detail? I guess throwing a lot of exceptions frequently may introduce performance issues, but not sure why. Is it because of the stack tracing?

Collapse
damxipo profile image
Damian Cipolat Author

Maybe the problem Is hoy don't catch the exceptoins very well.Seriously, it's the 1st time I've heard that throwing exceptions loses Performance. but I want to see how you base it, I don't say no but I am working like this on a project and we didn't lose performance

Collapse
danielpdev profile image
danielpdev

Yes, you are right. It's because of the stack tracing. As it needs to build your stack trace and it walks through the call stack to collect all required information like method names, line numbers etc.