Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

c# - Wrap every method in try-catch or specific part of code

My senior colleague tells me to wrap every method within a try-catch block so they can trace where exceptions occurs to help debug issues quicker. Is it better to wrap every method in a Try Catch such as this to:

Public int foo()
{
   try
   {
       //do something
   }catch(Exeception ex)
   {
       //do something with ex
   }
}

Or is it better to catch exceptions where I think they may occur? E.g. doing something with an array may cause the IndexOutOfRangeException will occur.

//wrap this in try catch
    int[] array = new int[3];

                array[0] = 1;
                array[1] = 2;
                array[2] = 3;
                array[3] = 4;

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The try block contains the guarded code that may cause the exception. The block is executed until an exception is thrown or it is completed successfully.

You can have a look on How often should I use try and catch

The basic rule of thumb for catching exceptions is to catch exceptions if and only if you have a meaningful way of handling them.

Don't catch an exception if you're only going to log the exception and throw it up the stack. It serves no meaning and clutters code.

Do catch an exception when you are expecting a failure in a specific part of your code, and if you have a fallback for it.

Of course you always have the case of checked exceptions which require you to use try/catch blocks, in which case you have no other choice. Even with a checked exception, make sure you log properly and handle as cleanly as possible.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...