In: Computer Science
in C#, What is an exception and what are the advantages of exception handling? What are the differences between the traditional error-handling methods and the object-oriented exception-handling methods and when should you use each one? Provide three to four paragraphs detailing your findings/views on these questions..provide examples with a simple code also..
What is an exception in c# ?
An exception will be a situation that arises during the execution of a program. A C# exception will be a response to such a situation . It will arise when the program is running. Ex,divide by zero.
When an exception arise we will jump to some other part of the code and then handle it.
Basically there are 4 blocks that are present to handle the exception. They try, catch, throw, finally.
try : It is a block which can throw an exception when the program is in the execution. The code is tried for the presence of exception hence the name "try".
catch : It is the block that catches exception and branches the program to a different part of code where the exception is handled.
throw : When the problem comes up, this part of the program throws up exception.
finally : These are the set of exceptions that will be executed irrespective of whether there is an exception or not.
What are the advantages of exception handling in c# ?
Differences in traditional error-handling methods and the object-oriented exception-handling methods ? Which one to use ?
The traditional error handling method is actually not any method at all. It only has the throw statement that throws the exception whenever it arises to handle it the way it should be handled. The throw statement branches to the catch statement. In order for any catch clause to pass control to the next catch on the stack, it must end by issuing a new throw statement.
Exceptions can also be considered as the classes as in object oriented programming. There are many exception classes in c# library. Prefer predefined exception classes instead of programming your own exception classes. An exception is seen as an object. All the relevant information regarding an exception is encapsulated in the object. These errors are classified and has a class hierarchy. They have their own methods of handling the errors. Hence because of this fact one should use the object oriented error handling methods because they are already present and one need not waste his own time on that.