问题
I want to ask what is the advantage
and disadvantages
of using try/catch
? and when I must use it and when I must not use it ?
回答1:
When you are using some external controls/dlls in your application and you are not sure about its functioning and you do not want an error in that external control to stop your own application then you can use Try/ Catch. It will not entirely stop your application because of the fatal error in that control. But the part of your code using that control would not function.
This does not mean that you can use Try Catch in your own code to avoid fatal errors this may cause serious flaw in your application.
Try/Catch can generally be used to debug an application and after that you can remove the Try/Catch block.
回答2:
Try-Catch-Finally statements are really powerful structure that help your program to be run flawless on most systems. It is a great error handling mechanism that helps your program not to crash. I want to star with this mechanism's disadvanteges as there are so little disadvanteges; Firstly, while working inside the try-catch statement you will lose some performance because some internal mechanism is checking for any exception to be catched however this performance loss is ignorable in current systems and this loss is so little when compared to the idea of starting whole program from the beginning because of a crash that happened due to not catched exception. Secondly, the concept of try-catch mechanism is a little bit hard to understand at the beginning, you should consider where and when to use try-catch statements well. However it is one of the most east to understand concept in complex structures in programming. Looking at the advantages side; Exception catching mechanism helps you to decide whatever you want to do in case of exception occurance. For example, thinking an online game when countering exception that shows loss of connection to the server you may let user to play offline and another person may decide to kick him out of the game and tell the gamer that he has been disconnected. Also, exception system makes it possible to create and use frameworks as framework coder tells you that an exception is occured when you are using his framework and you will do the job how you will react encountering this exception. Finally, it helps you to simplify your error detection system. Consider executing each method inside an if-else statement and see if an error is o cured, it will get messy soon and you will not be able to read your own code after a while. However in try-catch block you can do tens-hundreds operations that may fail and simply encapsulate the code into a simple try-catch block. Not more is coming to my mind right now, but hope this helps you to understand why using try-catch is benefial.
来源:https://stackoverflow.com/questions/14813877/advantages-and-disadvantages-of-using-try-catch