110 likes | 148 Views
Exception Handling. Chapter 13 Dr. Abraham. Pseudocode. Perform task If the preceding task did not execute correctly perform error processing Perform next task If the preceding task did not execute correctly perform error processing
E N D
Exception Handling Chapter 13 Dr. Abraham
Pseudocode • Perform task • If the preceding task did not execute correctly perform error processing • Perform next task • If the preceding task did not execute correctly perform error processing • --allows programmer to remove error-handling from main-line of the program execution--
Example of exception hierarchy • Exception • formatException • ArithmeticException • Overflow Exception • Divideby Zero Exception • All exceptions are subclasses of the Exception class. • An application can communicate with its users through a messageBox.
Catching an exception • Try-catch blocks. • Place try block around statements that might create an exception. • Exception Handler: Immediately after the try block, code a catch block that contains statements that would be executed if an exception occurred.
Example program I wrote: • I created four separate methods to do a simple calculation. The first one without any error handler. The second, with error handler to catch division by zero. The third, to handle format error caused by converting one type to another. The fourth combining the two known exceptions and anything else. • I explain the code in class. You may be required to do something similar on the exam. So, pay attention.
More than one exceptions thrown by try block • You can have multiple catch blocks to handle each error personalized by you. • You can have catch block to simply display windows messages.
Finally block • Finally block after all the catch blocks to code for things to do whether error occurred or not. This is usually used to free any system resources. • It is used to prevent resource leaks (example, files left open) and memory leak s (example, memory not deallocated).
Throwing exceptions • You can throw exceptions created by you. • Through keyword followed by new keyword: If (monthlyInvestment <=0) Throw new Exception(“Monthly Investment must be greater than 0”);
When to throw • When a method encounters a situation where it is not able to complete its task • When you want to catch the eception and perform some processing then through the exception again
Termination and Resumption Models • When CLR detects a problem an exception is thrown. At the point the exception is detected is called the throw point. • The control now transfers to the catch block. After the catch block the control does not transfer back to the throw point automatically. The program resumes after the catch blocks. This is known as the Termination Model of Exception Handling. • C# does not allow you to resume at the next statement after the throw point. Windows Form based programs don’t need to resume.