I've seen several approaches of exception handling. Two most common patterns I've seen are:
Which is a better practice if there is one? Or what situations would you choose one approach over the another?
It's not recommended nor economical to put try-catch in every function and block code. Instead, create a separate class for exception handling and log exceptions here, then show or handle these exceptions.
How to Handle an Exception. Java provides two different options to handle an exception. You can either use the try-catch-finally approach to handle all kinds of exceptions. Or you can use the try-with-resource approach which allows an easier cleanup process for resources.
By using exceptions to manage errors, Java programs have the following advantages over traditional error management techniques: Advantage 1: Separating Error Handling Code from "Regular" Code. Advantage 2: Propagating Errors Up the Call Stack. Advantage 3: Grouping Error Types and Error Differentiation.
This depends on your application and is a design choice, though option 1 is very messy. You should only catch exceptions you are prepared to handle in someway, not arbitrarily catching every one. In most languages the exception will have a stack trace for you to look at so logging at every level is unnecessary. When I say handle in some way that may be to log and rethrow, or it may be to log, notify the user of some error, and continue to run
As a side note, you should not be using exceptions as logic in your code. If you find yourself using try catch blocks as flow control then you should think of a redesign. Exceptions are just that, exceptional.
Option 1 is considered as bad practice and should be avoided, and option 2 is the best practice which you should follow.
Principle of exception handling is by default let exceptions throw naturally and catch them on the top level like option 2. Just only one case you should catch exception is you want to do some business logic based on exceptions. If you don't process business logic, don't catch.
More cons of option 1:
Lots of try-catch and re-throw makes your code less readable,
Think about catching exceptions in every methods and log them will make log file log the same exception info which is not necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With