Everyone know that : “Exceptions come at a cost, and they are expensive. They have a performance impact on the software and a maintenance overhead.”
Is that right ? Yes, absolutely. Every developers know this.
So that , if you are trying to “Try Catch” every functions in your code because you don’t know what exception will be happen with your code. I think it not a good way to handling the exception.
Exceptions are meant to be exceptional. Keep in mind that.
Every application will has exceptions:
- Network exception
- External library exception
- Un-handled case transaction
And throwing exception just a way we pass exception data from lower level layer to higher level layer and each layer can handle exception data if it want and swallow or rethrow it.
Throwing exception is not wrong. But because it has problem so that we need consider using it for suitable scenario.
“If you’re validating some data, you usually shouldn’t be using exceptions to signal validation failures. Here I describe how I’d refactor such code into using the Notification pattern.” Martin Fowler
If you are trying to throwing an exception in validation. I don’t think a good practice :
When you ask your friends: why they have used the try-catch, the answer is usually that they are trying to avoid the application producing unexpected errors. You might ask, “Why don’t you wrap the whole application in a try-catch?”, though it could be mistaken as flippant, it does promote the right thinking.
Once again , you shouldn’t need to catch all exceptions in every code. That why we have Global Exception Handling. We can make separation of concern and put all general exception handling logic in one place.
If you are .NET programmer. Please check : https://code-maze.com/global-error-handling-aspnetcore/
Throwing exception still good for un-handled transaction case that you need to stop this transaction immediately and don’t know what to do then you throw exception or let other layer handling this.