click below
click below
Normal Size Small Size show me how
Chapter 13
Exception Handling: A Deeper Look
Term | Definition |
---|---|
Exception | Indicates that a problem occurred during a program's execution |
Exception Thrown | AN exception is thrown when a method detects a problem and is unable to handle it |
Using DEBUG > Start Debugging | If you run an app using the DEBUG > Start Debugging menu option and an exception occurs, the IDE displays a dialog with information about the exception, a Break button, and a Continue button |
Break Button | You can click the Break button to pause the program at the line where the exception occurred, allowing you to analyze the program's state and debug the program |
Stack Trace | The several lines of information displayed in response to invalid input. This information includes the exception class's name in a message indicating the problem that occurred and the path of execution that led to the exception, method by method. |
1. Stack Trace "at" Line | A line in a stack trace that indicates a line of code in the particular method that was executing when the exception occurred. |
2. Stack Trace "at" Line | The "at" line contains the namespace, class and method in which the exception occurred, the location and name of the file containing the code, and the line number where the exception occurred. |
DivideByZeroException | When a program divides an integer by 0, the CLR throws a DivideByZeroException(namespace System) |
Throw Point | The initial point in which the exception occurred. The first "at" line in the stack trace indicates the exception's throw point |
FormatException | A FormatException(namespace)System occurs, for example, when Convert method ToInt32 receives a string that does not represent a valid integer |
1. Int32.TryParse Method | One way to validate input is to use the this method, which converts a string to an int value if possible. This method requires two arguments - one is the string to parse and the other is the variable in which the converted value is to be stored. |
2. Int32.TryParse Method | The method returns a bool value that's true only if the string was parsed successfully. If the string could not be converted, the value 0 is assigned to the second argument, which is passed by reference so its value can be modified in the calling method. |
try Block | Encloses the code that might throw exceptions, as well as the the code that's skipped when an exception occurs |
1. catch Block | Exception-handling code appears in a catch block. In general, when an exception occurs in a try block, a corresponding catch block catches the exception and handles it. |
2. catch Block | Ex: catch(FormatException formatException).. {.. Console.Writeline("\n" + formatException.Message);.. Console.Writeline("You must enter two integers. Please try again.\n").. } |
General catch Clause | A catch block that does not specify an exception type. This type of catch block catches all exception types. At least one catch block and/or a finally block must immediately follow a try block. |
Uncaught Exception(Unhandled Exception) | An exception for which there's no matching catch block |
Using DEBUG > Start Debugging | If you run an app from a non-Express version of Visual Studio by using DEBUG > Start Debugging and the runtime environment detects an uncaught exception, the app pauses, and the Exception Assistant window appears |
1. Components of the Exception Assistant Window | This window contains... 1. A line pointing from the Exception Assistant to the line of code that caused the exception.. 2. The type of the exception.. |
2. Components of the Exception Assistant Window | 3. Troubleshooting tips with links to helpful information on what might have caused the exception and how to handle it.. 4. Links to view or copy the complete exception details. |
Termination Model of Exception Handling | The model of exception handling in which after the exception is handled, program control does not return to throw point because the try block has exited(causes any local variables to go out of scope). Rather, control resumes after the first catch block. |
Resumption Model of Exception Handling | Some languages use this exception handling model, in which, after an exception is handled, control resumes just after the throw point |
try Statement | The try block and its corresponding catch and finally blocks together for a try statement |
Class Exception | In C#, the exception-handling mechanism allows only objects of class Exception(namespace System) and its derived classes to be thrown and caught. This class is the base class of .NETS's exception class hierarchy |
Class SystemException | An important derived class which the CLR generates. Many of these exceptions can be avoided if apps are coded properly |
IndexOutOfRangeException | An exception of this type is thrown if a program attempts to access an out-or-range array index. This is a derived class of SystemException |
NullReferenceException | An exception that occurs when a program uses a reference-type variable to call a method when the reference has a value of null. This is a derived class of SystemException |
Other CLR Thrown Exceptions | Other exceptions thrown by the CLR include OutOfMemoryException, StackOverflowException, and ExecutionEngineException, which are thrown when something goes wrong that causes the CLR to become unstable |
Memory Leak | Occurs when a program allocates memory(as C# programmers do via keyword new), but does not deallocate the memory when it's no longer needed. Usually this is not an issue in C# because the CLR performs garbage collection of memory that's no longer needed |
finally Block | Is guaranteed to execute regardless of whether the try block executes successfully or an exception occurs. The finally block is an ideal location to place resource-release code for resources that are acquired and manipulated in the corresponding try block |
Performance Tip 13.1 | As a rule, resources should be released as son as they're no longer needed in a program. This makes them available for reuse promptly |
finally Block Placement | If one or more catch blocks follow try block, finally block is optional. If no catch blocks follow try block, finally block must appear immediately after try block. If any catch blocks follow a try block, the finally block must appear after catch blocks |
1. throw Statement | Executing a throw statement indicates that a problem has occurred in the code. You can throw exceptions by using the throw statement. A throw statement specifies an object to be thrown. |
2. throw Statement | The operand of a throw statement can be of type Exception or of any type derived from class Exception. Ex: throw new Exception("Exception in ThrowExceptionsWtihCatch"); |
1. using Statement | The using statement(not using directive) simplifies writing code in which you obtain a resources, use the resource in a try block, and release the resource in a corresponding finally block. |
2. using Statement | A file processing app could process a file with a using statement to ensure that the file is closed properly when it's no longer needed. The resource must be an object that implements the IDisposable interface and therefore has a Dispose method |
1. using Statement General Form | Ex: using(ExampleClass exampleObject = new ExampleClass()).. {.. exampleObject.SomeMethod().. }.... where ExampleClass is a class that implements the IDisposable interface. |
2. using Statement General Form | This code creates an object of type ExampleClass and uses it in a statement, then calls its Dispose method to release any resource used by the object. |
3. using Statement General Form | The using statement implicitly places the code in its body in a try block with a corresponding finally block that calls the object's Dispose method. |
Class Exception Properties | Exception types derived from class Exception, which has several properties. These are frequently are used to formulate error messages indicating a caught exception. Two important properties are Message and StackTrace |
Property Message | Stores the error message associated with an Exception object. This message can be a default message associated with an exception type or a customized message passed to an Exception object's constructor when the Exception object is thrown |
Property StackTrace | Contains a string that represents the method-call stack. The StackTrace represents the series of methods that have not finished processing at the time the exception occurs |
InnerException | Another Exception property used frequently by class library programmers. Typically, you use this property to "wrap" exception objects caught in your code, so that you then can throw new exception types specific to your libraries |
Other Exception Properties | Class Exception provides other properties, including HelpLink, Source, and TargetSite |
Property HelpLink | Specifies the location of the help file that describes the problem that occurred. This property is null if no such file exists |
Property Source | Specifies the name of the app or object that caused the exception |
Property TargetSite | Species the method where the exception originated |
Stack Unwinding | When an exception is thrown but not caught in a particular scope, the method-call stack is "unwound", and an attempt is made to catch the exception in the next outer try block |
User-Defined Exception Classes | These classes should derived directly or indirectly from class Exception of namespace System. When you create code that throws exceptions, they should be well documented, so that other developers who use your code will know how to handle them |