Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception handling practices top level vs every function

Tags:

c#

.net

exception

I've seen several approaches of exception handling. Two most common patterns I've seen are:

  • try catch on every function, log the exception and rethrow
  • try catch on the top most level (Like main function), log the exception and rethrow

Which is a better practice if there is one? Or what situations would you choose one approach over the another?

like image 987
l46kok Avatar asked Oct 24 '12 04:10

l46kok


People also ask

Should you try catch every function?

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.

What are the two different ways you can handle an exception?

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.

What are the advantages of exception hierarchy?

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.


2 Answers

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.

like image 160
user815512 Avatar answered Oct 05 '22 11:10

user815512


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:

  1. Lots of try-catch and re-throw makes your code less readable,

  2. Think about catching exceptions in every methods and log them will make log file log the same exception info which is not necessary.

like image 26
cuongle Avatar answered Oct 05 '22 11:10

cuongle