2009 pearson education, inc. all rights reserved. 1 13 exception handling many slides modified by...
Post on 21-Dec-2015
213 Views
Preview:
TRANSCRIPT
2009 Pearson Education, Inc. All rights reserved.
1
1313
ExceptionHandling
Many slides modified by Prof. L. Lilien (even many without explicit message).
Slides added by L.Lilien are © 2006-2009 Leszek T. Lilien. Permision to use for non-commercial purposes slides added by L.Lilien’s will be gladly granted upon a written (e.g., emailed) request.
2009 Pearson Education, Inc. All rights reserved.
2
13.1 Introduction
13.2 Exception Handling Overview
13.3 Example: Divide by Zero without Exception Handling
13.4 Example: Handling DivideByZeroExceptions and FormatExceptions
13.5 .NET Exception Hierarchy
13.6 finally Block
13.7 Exception Properties
13.8 User-Defined (Programmer-Defined) Exception Classes
2009 Pearson Education, Inc. All rights reserved.
3
13.1 Introduction
• Exception– Indication of a problem during program execution
- Problems are exceptional, normally no problems
• Exception handling– Enables programmers to create application that can handle
exceptions- Enable clear, robust and more fault-tolerant programs
Slide modified by L. Lilien
2009 Pearson Education, Inc. All rights reserved.
4
++READ LATER++ 13.1 Introduction (Cont.)
Error-Prevention Tip 13.1
Exception handling helps improve a program’sfault tolerance.
2009 Pearson Education, Inc. All rights reserved.
5
13.2 Exception Handling Overview
• Pseudocode with included error processing code
Perform a 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
…
Slide added by L. Lilien
2009 Pearson Education, Inc. All rights reserved.
6
13.2 Exception Handling Overview – Cont.
• Including error processing code in a program intermixes program logic with error-handling logic
– Difficult to read, maintain, debug
– Better to separate program logic from error-handling logic
- Errors happen infrequently
- If many errors, placing checks for errors in program slows it down unnecessarily
Unnecessarily bec. most checks will not find errors
• Exception handling allows to remove error-handling code from the “main line” program execution
– Improves program clarity
– Enhances modifiability
Slide modified by L. Lilien
2009 Pearson Education, Inc. All rights reserved.
7
13.2 Exception Handling Overview – Cont.
• Keywords for exception handling– try{ <block of code in which exceptions might occur> }
– catch (<exception_parameter>) // 1 or more following each try { <how to handle this type of exception>}Note: If no “(<exception_parameter>)”, catch handles all exception types
– finally // optional, follows catch{ <codes present here will always execute – whether exception or not> }
• We’ll see how they are used in an example
Slide added by L. Lilien
2009 Pearson Education, Inc. All rights reserved.
8
++READ LATER++ 13.2 Exception Handling Overview – Cont.
• How exception detected?
– By a method called in a program
– By CLR (Common Language Runtime) system
• What happens when exception detected?
– Method or CLR throws an exception- Throw point – point at which exception was thrown
Important for debugging
• Exceptions are objects– Inherit from System.Exceptions
2009 Pearson Education, Inc. All rights reserved.
9
++READ LATER++ 13.2 Exception Handling Overview – Cont.
• Exception handling scenario– Exception occurs in a try block
– The try block expires (terminates immediately)- Therefore, we say that C# follows the termination model of exception handling
– CLR searches for the catch block (associated with this try block) matching the exception
- Among n catch blocks following this try block
- ‘Matching” – comparing the thrown exception’s type T1 and catch’s exception parameter type T2
Match – if they are identical or T1 is a derived class of T2
– If a match: (a) Code within the catch handler is executed
(b) Remaining catch blocks are ignored
– Execution resumed at the first instruction following this try-catch sequence
Slide modified by L. Lilien
2009 Pearson Education, Inc. All rights reserved.
10
++READ LATER++ 13.2 Exception Handling Overview – Cont.
• If no exception in a try block => catch blocks for this try are ignored
– Execution resumed at the first instruction following this try-catch sequence
• IF no matching catch
or:
IF exception occurs in a statement that is not in a try block
THEN:– the method containing the statement terminates immediately
– CLR attempts to locate an enclosing try block in a calling method (this is called “Stack unwinding”)
Slide modified by L. Lilien
2009 Pearson Education, Inc. All rights reserved.
11
13.3 Example: Divide by Zero without Exception Handling
++READ LATER++ • If you run using Debug > Start Debugging, the program
pauses at the line where an exception occurs (see p. 593/-1)
• If you run using the application:- from a Command Prompt window (see p. 595/1-ed.3)
– OR- walking down directory hierarchy down to …/<project name>/bin/debug
– When an error arises, a dialog indicates that the application has encountered a problem and needs to close
– An error message describing the problem is displayed
2009 Pearson Education, Inc. All rights reserved.
12
1 // Fig. 13.1: DivideByZeroNoExceptionHandling.cs
2 // Integer division without exception handling.
3 using System;
4
5 class DivideByZeroNoExceptionHandling
6 {
7 static void Main()
8 {
9 // get numerator and denominator
10 Console.Write( "Please enter an integer numerator: " );
11 int numerator = Convert.ToInt32( Console.ReadLine() );
12 Console.Write( "Please enter an integer denominator: " );
13 int denominator = Convert.ToInt32( Console.ReadLine() );
14
15 // divide the two integers, then display the result
Outline
DivideByZeroNoExceptionHandling.cs
( 1 of 2 )
• Example problem:
Calculate integer result of dividing one input integer by another input integer.
• In this example, we have no explicit exception handling
• Still, the system throws an exception when a method detects a problem (next slide)
Converting values can cause a FormatException.
Converting values can cause a FormatException.
2009 Pearson Education, Inc. All rights reserved.
1316 int result = numerator / denominator;
17 Console.WriteLine( "\nResult: {0:D} / {1:D} = {2:D}",
18 numerator, denominator, result );
19 } // end Main
20 } // end class DivideByZeroNoExceptionHandling Please enter an integer numerator: 100 Please enter an integer denominator: 7 Result: 100 / 7 = 14 Please enter an integer numerator: 100 Please enter an integer denominator: 0
Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero. at DivideByZeroNoExceptionHandling.Main() in C:\examples\ch13\Fig13_01\DivideByZeroNoExceptionHandling\ DivideByZeroNoExceptionHandling\
DivideByZeroNoExceptionHandling.cs: line 16
Outline
Division can cause a DivideByZeroException.
DivideByZeroNoExceptionHandling.cs
( 2 of 2 )
Stack trace
Please enter an integer numerator: 100 Please enter an integer denominator: hello
Unhandled Exception: System.FormatException: Input string was not in a correct format. at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToInt32(String value) at DivideByZeroNoExceptionHandling.Main() in C:\examples\ch13\Fig13_01\DivideByZeroNoExceptionHandling\ DivideByZeroNoExceptionHandling\
DivideByZeroNoExceptionHandling.cs: line 13
Stack trace
2009 Pearson Education, Inc. All rights reserved.
14
++READ LATER++13.3 Example: Divide by Zero without Exception Handling (Cont.)
• Additional information—known as a stack trace —displays the exception name and the path of execution that led to the exception.
• Each “at” line in the stack trace indicates a line of code in the particular method that was executing when the exception occurred.
• This information tells where the exception originated, and what method calls were made to get to that point.
2009 Pearson Education, Inc. All rights reserved.
15
++READ LATER++13.3 Example: Divide by Zero without Exception Handling (Cont.)
• When entered “0” as denominator :– A DivideByZeroException occurs
- Since can’t divide by zero
• When entered “hello” as denominator :– A FormatException occurs
- Since method Convert .ToInt32 receives a string that is not a valid integer
• Note: A program may continue executing even though an exception has occurred and a stack trace has been printed
– In such cases, the application may produce incorrect results
2009 Pearson Education, Inc. All rights reserved.
16
13.4 Example: Handling DivideByZeroExceptions and FormatExceptions
++READ LATER++• The Int32.TryParse method converts a string to an int value if possible
– It requires two arguments- one is the string to parse
- the other is the variable in which the converted value is to be stored
– It returns true if the string was parsed successfully
– If the string could not be converted, the value 0 is assigned to the second argument
2009 Pearson Education, Inc. All rights reserved.
17
Outline
a) Performing integer division
b) Dividing by zero
d) Entering a string valuee) Error message
c) Error message
DivideByZeroTest.cs
( 4 of 4 )
Expected behavior of the next WF app:
2009 Pearson Education, Inc. All rights reserved.
18
1 // Fig. 13.2: DivideByZeroTest.cs
2 // FormatException and DivideByZeroException handlers.
3 using System;
4 using System.Windows.Forms;
5
6 namespace DivideByZeroTest
7 {
8 public partial class DivideByZeroTestForm : Form
9 {
10 public DivideByZeroTestForm()
11 {
12 InitializeComponent();
13 } // end constructor
14
• This Windows Forms app uses exception handling to process DivideByZeroExceptions and FormatExceptions
• This program demonstrates how to catch and handle such exceptions
Outline
DivideByZeroTest.cs
( 1 of 3 )
2009 Pearson Education, Inc. All rights reserved.
1915 // obtain 2 integers from the user
16 // and divide numerator by denominator
17 private void divideButton_Click( object sender, EventArgs e )
18 {
19 outputLabel.Text = ""; // clear Label OutputLabel
20
21 // retrieve user input and calculate quotient
22 try
23 {
24 // Convert.ToInt32 generates FormatException
25 // if argument cannot be converted to an integer
26 int numerator = Convert.ToInt32( numeratorTextBox.Text );
27 int denominator = Convert.ToInt32( denominatorTextBox.Text );
28
29 // division generates DivideByZeroException
30 // if denominator is 0
31 int result = numerator / denominator;
32
33 // display result in OutputLabel
34 outputLabel.Text = result.ToString();
35 } // end try
OutlineDivideByZeroTest.cs ( 2 of 3 )
36 catch ( FormatException )
37 {
38 MessageBox.Show( "You must enter two integers.",
39 "Invalid Number Format", MessageBoxButtons.OK,
40 MessageBoxIcon.Error );
41 } // end catch
42 catch ( DivideByZeroException divideByZeroExceptionParameter )
43 {
44 MessageBox.Show( divideByZeroExceptionParameter.Message,
45 "Attempted to Divide by Zero", MessageBoxButtons.OK,
46 MessageBoxIcon.Error );
47 } // end catch
48 } // end method divideButton_Click
49 } // end class DivideByZeroTestForm
50 } // end namespace DivideByZeroTest
This catch block catches and handles a FormatException.
This catch block catches and handles a DivideBy-ZeroException.
2009 Pearson Education, Inc. All rights reserved.
20
Outline
a) Performing integer division
b) Dividing by zero
d) Entering a string valuee) Error message
c) Error message
DivideByZeroTest.cs
( 3 of 3)
Output of DivideByZeroTest program
2009 Pearson Education, Inc. All rights reserved.
21++READ LATER++ 13.4 Example: Handling DivideByZeroExceptions and FormatExceptions
• Error catching (by a method or CLR)
– Method Convert.ToInt32 will automatically detect invalid representations of an integer
- Method generates a FormatException
– CLR automatically detects division by zero- CLR generates a DivideByZeroException
2009 Pearson Education, Inc. All rights reserved.
22
++READ LATER++ 13.4 Example: Handling DivideByZeroExceptions and FormatExceptions (Cont.)
13.4.1 Enclosing Code in a try Block
• A try block encloses code that might throw exceptions and code that is skipped when an exception occurs.
2009 Pearson Education, Inc. All rights reserved.
23
++READ LATER++ 13.4 Example: Handling DivideByZeroExceptions and FormatExceptions (Cont.)
13.4.2 Catching Exceptions• When an exception occurs in a try block, a corresponding catch block catches the exception and handles it
– At least one catch block must immediately follow a try block.
• A catch block can specify an exception parameter representing the exception that the catch block can handle
– Optionally, you can include a catch block that does not specify an exception type to catch all exception types.
2009 Pearson Education, Inc. All rights reserved.
24
++READ LATER++ 13.4 Example: Handling DivideByZeroExceptions and FormatExceptions (Cont.)
13.4.3 Uncaught Exceptions
• An uncaught exception (or unhandled exception) is an exception for which there is no matching catch block
2009 Pearson Education, Inc. All rights reserved.
25
++READ LATER++ 13.4 Example: Handling DivideByZeroExceptions and FormatExceptions (Cont.)
Throw point Exception Assistant
• When you run the application from Visual Studio with debugging, a window called the Exception Assistant (Fig. 13.3-below) appears.
2009 Pearson Education, Inc. All rights reserved.
26
++READ LATER++ 13.4 Example: Handling DivideByZeroExceptions and FormatExceptions (Cont.)
13.4.4 Termination Model of Exception Handling• When a method called in a program or the CLR detects a problem,
the method or the CLR throws an exception– The point at which an exception occurs is called the throw point
2009 Pearson Education, Inc. All rights reserved.
27
++READ LATER++ 13.4 Example: Handling DivideByZeroExceptions and FormatExceptions (Cont.)
• Two kinds of exception handling (p.600/2 -ed.3):
1) “Terminate” model of exception handling – used in C#After exception handling, control resumes after the last catch block
2) “Resumption” model of exception handling After exception handling, control resumes just after the throw point
Slide modified by L. Lilien
2009 Pearson Education, Inc. All rights reserved.
28
++READ LATER++ 13.4 Example: Handling DivideByZeroExceptions and FormatExceptions (Cont.)
• If an exception occurs in a try block, program control immediately transfers to the first catch block matching the type of the thrown exception
• After the exception is handled, program control in C# resumes after the last catch block
– Since C# uses the termination model of exception handling
2009 Pearson Education, Inc. All rights reserved.
29
++READ LATER++ 13.4 Example: Handling DivideByZeroExceptions and FormatExceptions (Cont.)
Common Programming Error 13.1Logic errors can occur if you assume that after an exception is handled, control will return to the first statement after the throw point.
Common Programming Error 13.2A catch block can have at most one parameter
Specifying a comma-separated list of parameters in a catch block is a syntax error
2009 Pearson Education, Inc. All rights reserved.
30
13.5 .NET Exception Hierarchy
• .NET Framework exception hierarchy (in the System namespace)
– Base class Exception
– Derived class ApplicationException
– Derived class SystemException
- Derived class IndexOutOfRangeExceptionThrown, e.g., on an attempt to access out-of-range array
subscript
- Derived class NullReferenceException Thrown, e.g., on an attempt to reference a non-existing
object
- Derived class … (many others)…
• In C#, exception-handling mechanisms allows to throw/catch only objects of class Exception and its derived classes Slide modified by L. Lilien
2009 Pearson Education, Inc. All rights reserved.
31
13.5 .NET Exception Hierarchy (Cont.)
• Derived class ApplicationException– Programmers use it to create exception classes specific to their
applications– Low risk of program stopping upon ApplicationException
- Typically, programs can recover from ApplicationExceptions & continue execution
• Derived class SystemException– CLR can generate runtime exceptions (derived from SystemException) at
any point during execution- Many can be avoided by proper coding- E.g., runtime exception: IndexOutOfRangeException- E.g., runtime reference to a non-existing object:
NullReferenceException– Typically, programs terminate upon SystemException
- Bec. programs can’t recover from most SystemExceptions
Slide modified by L. Lilien
2009 Pearson Education, Inc. All rights reserved.
32++READ LATER++ 13.5 .NET Exception Hierarchy (Cont.)
• Is MSDN Library (which provides Help) installed in your Visual Studio?
– If not, get it from C-208, and install it
• See full hierarchy of exception classes in .NET in Visual Studio:– Select >>Help>Index– Look up “Exception class”
• Benefit of exception hierarchy:– Instead of catch-ing each derived-class exception class
separately, catch the base-class exception– Much more concise– Useful only if the handling behavior is the same for the base
class and the derived classes
Slide added by L. Lilien
2009 Pearson Education, Inc. All rights reserved.
33++READ LATER++ 13.5 .NET Exception Hierarchy (Cont.)• How to find out that a program can cause an exception?
1) For methods in .NET Framework- Look at detailed method description in Visual Studio
Select >>Help>Index
Find the class.method in the index
Look up the “Exception” section in the document describing the method
Enumerates exceptions of the method Describes the reason why each occurs
- Example (p.603/1-ed.3) – Convert.ToInt32 can throw 2 exception types: FormatException and OverflowException
2) For CLR
… next page… Slide added by L. Lilien
2009 Pearson Education, Inc. All rights reserved.
34
• How to find out that a program can cause an exception? (Cont.)
2) For CLR
- More difficult – search C# Language Specifications (online) (on MSDN online at the Visual C# Developer Center:
http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx )
- In Visual StudioThe C# Language Specification available in Microsoft
Word in the VC#\Specifications\1033\ directory under your Visual Studio 2008 installation directory (e.g., in: C:\Program Files\Microsoft Visual Studio 9.0\VC#\Specifications\1033 )
- Example:
DivideByZeroException described in Section 16.4 (p. 419) of “C# Language Specification:”
Thrown when an attempt to divide an integral value by zero occurs.
Slide added by L. Lilien
++READ LATER++ 13.5 .NET Exception Hierarchy (Cont.)
2009 Pearson Education, Inc. All rights reserved.
35
• A catch block can use a base-class type to catch a hierarchy of related exceptions
• A catch block that specifies a parameter of type Exception can catch all exceptions
– This technique makes sense only if the handling behavior is the same for a base class and all derived classes
Common Programming Error 13.3The compiler issues an error if a catch block that catches a base-class exception is placed before a catch block for any of that class’s derived-class types
In this case, the base-class catch block would catch all base-class and derived-class exceptions, so the derived-class exception handler would never execute—a possible logic error
++READ LATER++13.5 .NET Exception Hierarchy
2009 Pearson Education, Inc. All rights reserved.
36
++READ LATER++ 13.5 .NET Exception Hierarchy (Cont.)
13.5.2 Determining Which Exceptions a Method Throws
• Example – determine which exceptions are thrown by Convert.ToInt32 method
– Search for “Convert.ToInt32 method” in the Index of the VS online documentation
– Select the document entitled Convert.ToInt32 Method (System)
– In the document that describes the method, click the link ToInt32(String)
– The Exceptions section indicates that method Convert.ToInt32 throws two exception types
2009 Pearson Education, Inc. All rights reserved.
37
++READ LATER++ 13.5 .NET Exception Hierarchy (Cont.)
Software Engineering Observation 13.1
If a method throws exceptions, statements that invoke the method directly or indirectly should be placed in try blocks, and those exceptions should be caught and handled
2009 Pearson Education, Inc. All rights reserved.
38
13.6 finally Block
• Programs frequently request and release resources dynamically
• Example 1:
– Memory is allocated for each object created (with new)
– Once object not needed, memory used by it should be released
– If memory is not released, memory leak (a specific type of a resource
leak) occurs
• ++SKIP++: Example 2:
– Operating systems typically prevent more than one program from manipulating a file
– Therefore, the program that needs file no more, should close it (i.e., release the file, a resource) so other programs can use it
– If the file is not closed, a resource leak occurs
2009 Pearson Education, Inc. All rights reserved.
39
13.6 finally Block (Cont.)
• So, resource leak can be defined as:
– Allocation of resources (files, memory, etc.) lasting too long- Longer than needed
• finally block
– Associated with a try block
– Ideal for placing resource deallocation code
- Prevents leak of resources allocated in its try block
– Executed immediately after catch handler or try block
– Required if no catch block is present
Optional if one or more catch handlers exist
– Executed if its try block entered
- Even if try block not completedSlide modified by L. Lilien
2009 Pearson Education, Inc. All rights reserved.
40
Error-Prevention Tip 13.2
The CLR does not completely eliminate memory leaks
The CLR will not “garbage collect” an object until the program contains no more references to that object and even then there may be a delay until the memory is required
Thus, memory leaks can occur if programmers inadvertently keep references to unwanted objects (i.e., the objects not needed any more)
++READ LATER++ 13.6 finally Block (Cont.)
2009 Pearson Education, Inc. All rights reserved.
41
++READ LATER++ 13.6 finally Block (Cont.)
• Exceptions often occur while processing resources
• Regardless of whether a program experiences exceptions, the program should close the file when it is no longer needed
• C# provides the finally block, which is guaranteed to execute regardless of whether an exception occurs
• This makes the finally block ideal to release resources from the corresponding try block
2009 Pearson Education, Inc. All rights reserved.
42
++READ LATER++ 13.6 finally Block (Cont.)
• Local variables in a try block cannot be accessed in the corresponding finally block, so variables that must be accessed in both should be declared before the try block.
Error-Prevention Tip 13.3
A finally block typically contains code to release resources acquired in the corresponding try block
This makes the finally block an effective mechanism for eliminating resource leaks
2009 Pearson Education, Inc. All rights reserved.
43
++READ LATER++ 13.6 finally Block (Cont.)
Performance Tip 13.1
As a rule, resources should be released as soon as they are no longer needed in a program
This makes them available for reuse promptly
Common Programming Error 13.4
Placing the finally block before a catch block is a syntax error
2009 Pearson Education, Inc. All rights reserved.
44
13.6 finally Block (Cont.)
• The throw statement– Allows a user/programmer to throw an exception at will
- E.g.:
throw new Exception("Exception in ThrowTest Method" );
- where the string passed to exception object’s constructor becomes exception object’s error message
– Can throw only an object of class Exception or one of its derived classes (SystemException, MyDivBbZeroException, etc)
– You can customize the exception type thrown from methods
Slide modified by L. Lilien
2009 Pearson Education, Inc. All rights reserved.
45
1 // Fig. 13.4: UsingExceptions.cs
2 // Using finally blocks.
3 // finally blocks always execute, even when no exception occurs.
4 using System;
5
6 class UsingExceptions
7 {
8 static void Main()
9 {
10 // Case 1: No exceptions occur in called method
11 Console.WriteLine( "Calling DoesNotThrowException" );
12 DoesNotThrowException();
13
14 // Case 2: Exception occurs and is caught in called method
15 Console.WriteLine( "\nCalling ThrowExceptionWithCatch" );
16 ThrowExceptionWithCatch();
17
18 // Case 3: Exception occurs, but is not caught in called method
19 // because there is no catch block.
20 Console.WriteLine( "\nCalling ThrowExceptionWithoutCatch" );
Outline
UsingExceptions.cs
( 1 of 8)
• This application (below) demonstrates that the finally block always executes (even when no exception occurs)
Main invokes method DoesNotThrowException.
Main invokes method ThrowExceptionWithCatch.
Calling DoesNotThrowException
In DoesNotThrowException
finally executed in DoesNotThrowException
End of DoesNotThrowException
Calling ThrowExceptionWithCatch
In ThrowExceptionWithCatch
Message: Exception in ThrowExceptionWithCatch
finally executed in ThrowExceptionWithCatch
End of ThrowExceptionWithCatch
Calling ThrowExceptionWithoutCatch
2009 Pearson Education, Inc. All rights reserved.
4621
22 // call ThrowExceptionWithoutCatch
23 try
24 {
25 ThrowExceptionWithoutCatch();
26 } // end try
27 catch
28 {
29 Console.WriteLine( "Caught exception from " +
30 "ThrowExceptionWithoutCatch in Main" );
31 } // end catch
32
33 // Case 4: Exception occurs and is caught in called method,
34 // then rethrown to caller.
35 Console.WriteLine( "\nCalling ThrowExceptionCatchRethrow" );
36
37 // call ThrowExceptionCatchRethrow
38 try
39 {
40 ThrowExceptionCatchRethrow();
41 } // end try
OutlineUsingExceptions.cs ( 2 of 8)
Main invokes method ThrowExceptionWithoutCatch.
Main invokes method ThrowExceptionCatchRethrow.
In ThrowExceptionWithoutCatch
finally executed in ThrowExceptionWithoutCatch
Caught exception from ThrowExceptionWithoutCatch in Main
Calling ThrowExceptionCatchRethrow
In ThrowExceptionCatchRethrow
Message: Exception in ThrowExceptionCatchRethrow
finally executed in ThrowExceptionCatchRethrow
2009 Pearson Education, Inc. All rights reserved.
4742 catch
43 {
44 Console.WriteLine( "Caught exception from " +
45 "ThrowExceptionCatchRethrow in Main" );
46 } // end catch
47 } // end method Main
48
49 // no exceptions thrown
50 static void DoesNotThrowException()
51 {
52 // try block does not throw any exceptions
53 try
54 {
55 Console.WriteLine( "In DoesNotThrowException" );
56 } // end try
57 catch
58 {
59 Console.WriteLine( "This catch never executes" );
60 } // end catch
Outline
Because the try block does not throw any exceptions, the catch block is ignored.
UsingExceptions.cs ( 3 of 8)
Caught exception from ThrowExceptionCatchRethrow in Main
Calling DoesNotThrowException
In DoesNotThrowException
2009 Pearson Education, Inc. All rights reserved.
48
61 finally
62 {
63 Console.WriteLine( "finally executed in DoesNotThrowException" );
64 } // end finally
65
66 Console.WriteLine( "End of DoesNotThrowException" );
67 } // end method DoesNotThrowException
68
69 // throws exception and catches it locally
70 static void ThrowExceptionWithCatch()
71 {
72 // try block throws exception
73 try
74 {
75 Console.WriteLine( "In ThrowExceptionWithCatch" );
76 throw new Exception( "Exception in ThrowExceptionWithCatch" );
77 } // end try
78 catch ( Exception exceptionParameter )
79 {
80 Console.WriteLine( "Message: " + exceptionParameter.Message );
81 } // end catch
OutlineThe finally block always executes.
The try block throws an exception.
The catch and finally blocks execute when the exception occurs.
UsingExceptions.cs ( 4 of 8)
finally executed in DoesNotThrowException
End of DoesNotThrowException
Calling ThrowExceptionWithCatch
In ThrowExceptionWithCatch
Message: Exception in ThrowExceptionWithCatch
2009 Pearson Education, Inc. All rights reserved.
49
82 finally
83 {
84 Console.WriteLine(
85 "finally executed in ThrowExceptionWithCatch" );
86 } // end finally
87
88 Console.WriteLine( "End of ThrowExceptionWithCatch" );
89 } // end method ThrowExceptionWithCatch
90
91 // throws exception and does not catch it locally
92 static void ThrowExceptionWithoutCatch()
93 {
94 // throw exception, but do not catch it
95 try
96 {
97 Console.WriteLine( "In ThrowExceptionWithoutCatch" );
98 throw new Exception( "Exception in ThrowExceptionWithoutCatch" );
99 } // end try
OutlineThe catch and finally blocks execute when the exception occurs.
The try block throws an exception.
UsingExceptions.cs ( 5 of 8)
finally executed in ThrowExceptionWithCatch
End of ThrowExceptionWithCatch
Calling ThrowExceptionWithoutCatch
In ThrowExceptionWithoutCatch
2009 Pearson Education, Inc. All rights reserved.
50
100 finally
101 {
102 Console.WriteLine( "finally executed in " +
103 "ThrowExceptionWithoutCatch" );
104 } // end finally
105
106 // unreachable code; logic error (returns to Main right after finally)
107 Console.WriteLine( "End of ThrowExceptionWithoutCatch" );
108 } // end method ThrowExceptionWithoutCatch
109
110 // throws exception, catches it and rethrows it
111 static void ThrowExceptionCatchRethrow()
112 {
113 // try block throws exception
114 try
115 {
116 Console.WriteLine( "In ThrowExceptionCatchRethrow" );
117 throw new Exception( "Exception in ThrowExceptionCatchRethrow" );
118 } // end try
OutlineThe finally block executes but the exception remains uncaught until after control returns to Main.
The try block throws an exception.
UsingExceptions.cs ( 6 of 8)
finally executed in ThrowExceptionWithoutCatch
Caught exception from ThrowExceptionWithoutCatch in Main
Calling ThrowExceptionCatchRethrow
In ThrowExceptionCatchRethrow
Statements following finally are not executed. The reason: there is an unhandled exception when finally finishes, so once the finally block is completed, execution returns to Main.
2009 Pearson Education, Inc. All rights reserved.
51
119 catch ( Exception exceptionParameter )
120 {
121 Console.WriteLine( "Message: " + exceptionParameter.Message );
122
123 // rethrow exception for further processing
124 throw;
125
126 // any code placed here would be unreachable code; logic error
127 } // end catch
128 finally
129 {
130 Console.WriteLine( "finally executed in " +
131 "ThrowExceptionCatchRethrow" );
132 } // end finally
133
134 // any code placed here is never reached (returns to Main after finally)
135 Console.WriteLine( "End of ThrowExceptionCatchRethrow" );
136 } // end method ThrowExceptionCatchRethrow
137 } // end class UsingExceptions
OutlineThe catch block rethrows the exception, which is then caught after control returns to Main. The catch and finally
blocks execute when the exception occurs.
UsingExceptions.cs
( 7 of 8)
Message: Exception in ThrowExceptionCatchRethrow
finally executed in ThrowExceptionCatchRethrow
Caught exception from ThrowExceptionCatchRethrow in Main
Statements following finally are not executed. The reason: there is an unhandled exception when finally finishes, so once the finally block is completed, execution returns to Main.
2009 Pearson Education, Inc. All rights reserved.
52 Calling DoesNotThrowException In DoesNotThrowException finally executed in DoesNotThrowException End of DoesNotThrowException Calling ThrowExceptionWithCatch In ThrowExceptionWithCatch Message: Exception in ThrowExceptionWithCatch finally executed in ThrowExceptionWithCatch End of ThrowExceptionWithCatch Calling ThrowExceptionWithoutCatch In ThrowExceptionWithoutCatch finally executed in ThrowExceptionWithoutCatch Caught exception from ThrowExceptionWithoutCatch in Main Calling ThrowExceptionCatchRethrow In ThrowExceptionCatchRethrow Message: Exception in ThrowExceptionCatchRethrow finally executed in ThrowExceptionCatchRethrow Caught exception from ThrowExceptionCatchRethrow in Main
Outline
UsingExceptions.cs
( 8 of 8)
2009 Pearson Education, Inc. All rights reserved.
53
Common Programming Error 13.5
It is a compilation error if the argument of a throw—an exception object—is not of class Exception or one of its derived classes.
Common Programming Error 13.6
Throwing an exception from a finally block can be dangerous. If an uncaught exception is awaiting processing when the finally block executes, and the finally block throws a new exception that is not caught in the finally block, the first exception is lost, and the new exception is passed to the next enclosing try block.
++READ LATER++ 13.6 finally Block (Cont.)
2009 Pearson Education, Inc. All rights reserved.
54
Error-Prevention Tip 13.4When placing code that can throw an exception in a finally block, always enclose the code in a try statement that catches the appropriate exception types
This prevents the loss of any uncaught and rethrown exceptions that occur before the finally block executes
Software Engineering Observation 13.2Do not place try blocks around every statement that might throw an exception—this can make programs difficult to read
It’s better to place one try block around a significant portion of code, and follow this try block with catch blocks that handle each possible exception
Then follow the catch blocks with a single finally block
Separate try blocks should be used when it is important to distinguish between multiple statements that can throw the same exception type
++READ LATER++ 13.6 finally Block (Cont.)
2009 Pearson Education, Inc. All rights reserved.
55
++READ LATER++ 13.6 finally Block (Cont.)
• The using statement simplifies writing code in which you obtain a resource.
• The general form of a using statement is:using ( ExampleObject e = new ExampleObject() ){ e.SomeMethod();
}
• Read subsection on the using statement - not to be confused with the using directive for using namespaces
– p. 610 (ed.3)
2009 Pearson Education, Inc. All rights reserved.
56
++READ LATER++ 13.6 finally Block (Cont.)
• The using statement code is equivalent to{ ExampleObject e = new ExampleObject();
try { e.SomeMethod(); } finally { if ( e != null ) ( ( IDisposable ) e ).Dispose(); } }
NOTE: Some components above were not discussed yet in class.
2009 Pearson Education, Inc. All rights reserved.
57
13.7 Exception Properties• Exception properties = properties of the Exception class
• Caught Exception objects have 3 properties (all shown in the next example)
1) Property Message Cf. Slide 50, line 121: exception object ‘exceptionParameter’
Console.WriteLine( "Message: " + exceptionParameter.Message );
- Stores the error message associated with an Exception object
May be a default message or customized
2) Property StackTrace
- Contains a string that represents the method call stack
- Represents sequential list of methods that were not fully processed when the exception occurred
- throw point - the exact location where exception occurred
2009 Pearson Education, Inc. All rights reserved.
58
13.7 Exception Properties (Cont.)
• Properties for a caught exception – cont.
3) Property InnerException
- Programmers “wrap” exception objects caught in their own code
Then can throw new exception types specific to their own code
- The original exception object remains “saved” in Inner Exception within the programmer-defined exception
- Example:
l. 26-27 in the following program
2009 Pearson Education, Inc. All rights reserved.
59
1 // Fig. 13.5: Properties.cs
2 // Stack unwinding and Exception class properties.
3 // Demonstrates using properties Message, StackTrace and InnerException.
4 using System;
5
6 class Properties
7 {
8 static void Main()
9 {
10 // call Method1; any Exception generated is caught
11 // in the catch block that follows
12 try
13 {
14 Method1();
15 } // end try
Outline• Our next example (below) demonstrates properties of
class Exception and stack unwinding
Properties.cs
( 1 of 5 )
2009 Pearson Education, Inc. All rights reserved.
60
16 catch ( Exception exceptionParameter )
17 {
18 // output the string representation of the Exception, then output
19 // properties InnerException, Message and StackTrace
20 Console.WriteLine( "exceptionParameter.ToString: \n{0}\n",
21 exceptionParameter );
22 Console.WriteLine( "exceptionParameter.Message: \n{0}\n",
23 exceptionParameter.Message );
24 Console.WriteLine( "exceptionParameter.StackTrace: \n{0}\n",
25 exceptionParameter.StackTrace );
26 Console.WriteLine( "exceptionParameter.InnerException: \n{0}\n",
27 exceptionParameter.InnerException );
28 } // end catch
29 } // end method Main
30
31 // calls Method2
32 static void Method1()
33 {
34 Method2();
35 } // end method Method1
36
Outline
Outputting properties of class Exception.
Method1 and Method2 are added to the method stack, and then unwind when they do not catch Method3’s exception.
Properties.cs
( 2 of 5 )
2009 Pearson Education, Inc. All rights reserved.
61
37 // calls Method3
38 static void Method2()
39 {
40 Method3();
41 } // end method Method2
42
43 // throws an Exception containing an InnerException
44 static void Method3()
45 {
46 // attempt to convert string to int
47 try
48 {
49 Convert.ToInt32( "Not an integer" );
50 } // end try
51 catch ( FormatException formatExceptionParameter )
52 {
53 // wrap FormatException in new Exception
54 throw new Exception( "Exception occurred in Method3",
55 formatExceptionParameter );
56 } // end catch
57 } // end method Method3
58 } // end class Properties
Outline
Method1 and Method2 are added to the method stack, and then unwind when they do not catch Method3’s exception.
Method3 catches then rethrows the exception.
Properties.cs
( 3 of 5 )
2009 Pearson Education, Inc. All rights reserved.
62
exceptionParameter.ToString: System.Exception: Exception occurred in Method3 ---> System.FormatException: Input string was not in a correct format. at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToInt32(String value) at Properties.Method3() in C:\examples\ch13\Fig13_05\Properties\ Properties\Properties.cs:line 49 --- End of inner exception stack trace --- at Properties.Method3() in C:\examples\ch13\Fig13_05\Properties\ Properties\Properties.cs:line 54 at Properties.Method2() in C:\examples\ch13\Fig13_05\Properties\ Properties\Properties.cs:line 40 at Properties.Method1() in C:\examples\ch13\Fig13_05\Properties\ Properties\Properties.cs:line 34 at Properties.Main() in C:\examples\ch13\Fig13_05\Properties\ Properties\Properties.cs:line 14
Outline
Properties.cs
( 4 of 5 )
exceptionParameter.Message starts and ends here (highlighted, < 1 line)
exceptionParameter.StackTrace starts here
exceptionParameter.InnerException starts here
2009 Pearson Education, Inc. All rights reserved.
63
exceptionParameter.Message: Exception occurred in Method3
exceptionParameter.StackTrace: at Properties.Method3() in C:\examples\ch13\Fig13_05\Properties\ Properties\Properties.cs:line 54 at Properties.Method2() in C:\examples\ch13\Fig13_05\Properties\ Properties\Properties.cs:line 40 at Properties.Method1() in C:\examples\ch13\Fig13_05\Properties\ Properties\Properties.cs:line 34 at Properties.Main() in C:\examples\ch13\Fig13_05\Properties\ Properties\Properties.cs:line 14
exceptionParameter.InnerException: System.FormatException: Input string was not in a correct format. at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToInt32(String value) at Properties.Method3() in C:\examples\ch13\Fig13_05\Properties\ Properties\Properties.cs:line 49
Outline
Properties.cs
( 5 of 5 )
2009 Pearson Education, Inc. All rights reserved.
64
++READ LATER++ 13.7 Exception Properties (Cont.)
Error-Prevention Tip 13.5
If the program database (PDB) file (that contains the debugging information for a method) is accessible to the IDE, the stack trace also includes line numbers
The first line number indicates the throw point, and subsequent line numbers indicate the locations from which the methods in the stack trace were called
PDB files are created by the IDE to maintain the debugging information for your projects
2009 Pearson Education, Inc. All rights reserved.
65
++READ LATER++ 13.7 Exception Properties (Cont.)
• When an exception occurs, a programmer might use a different error message or indicate a new exception type
• The original exception object is stored in the InnerException property
2009 Pearson Education, Inc. All rights reserved.
66
++READ LATER++ 13.7 Exception Properties (Cont.)
• Class Exception provides also other properties:– HelpLink specifies the location of a help file that describes the
problem
– Source specifies the name of the application or object that caused the exception
– TargetSite specifies the method where the exception originated.
2009 Pearson Education, Inc. All rights reserved.
67
++READ LATER++ 13.7 Exception Properties (Cont.)
• The method called most recently appears at the top of the stack; the first method called (Main) appears at the bottom
• The StackTrace represents the state of the method-call stack at the throw point
• The inner-exception information includes the inner exception stack trace
Error-Prevention Tip 13.6When catching and rethrowing an exception, provide additional debugging information in the rethrown exception
To do so, create an Exception object containing more specific debugging information, then pass the original caught exception to the new exception object’s constructor to initialize the InnerException property.
2009 Pearson Education, Inc. All rights reserved.
68
• User can create customized (a.k.a. user-defined or programmer-defined) exception classes
– Specific to the problems that occur in user’s program
• They should be derived from the class ApplicationException – Which is in turn derived from the class Exception
13.8 User-Defined (Programmer-Defined) Exception Classes
2009 Pearson Education, Inc. All rights reserved.
69
• Customized exception classes– Class name should end with “Exception”
- E.g., NegativeNumberException
– Should define three constructors- a parameterless constructor- a constructor that receives a string argument (the error message)- a constructor that receives a string argument and an Exception
argument (the error message and the inner exception object)
– User-defined exceptions must be well documented- So that other developers will know how to handle them
• Example of customized exception types (classes) – next Slide
++READ LATER++ 13.8 User-Defined (Programmer-Defined) Exception Classes
2009 Pearson Education, Inc. All rights reserved.
70
1 // Fig. 13.6: NegativeNumberException.cs
2 // NegativeNumberException represents exceptions caused by
3 // illegal operations performed on negative numbers.
4 using System;
5
6 namespace SquareRootTest
7 {
8 class NegativeNumberException : Exception
9 {
10 // default constructor
11 public NegativeNumberException()
12 : base( "Illegal operation for a negative number" )
13 {
14 // empty body
15 } // end default constructor
16
Outline
NegativeNumberException.cs
( 1 of 2 )
• Class NegativeNumberException (Fig. 13.6 - below) defines customized exceptions that occur when a program performs an illegal operation on a negative number.
Inheriting from class Exception.
Parameterless constructor.
2009 Pearson Education, Inc. All rights reserved.
71
17 // constructor for customizing error message
18 public NegativeNumberException( string messageValue )
19 : base( messageValue )
20 {
21 // empty body
22 } // end one-argument constructor
23
24 // constructor for customizing the exception's error
25 // message and specifying the InnerException object
26 public NegativeNumberException( string messageValue,
27 Exception inner )
28 : base( messageValue, inner )
29 {
30 // empty body
31 } // end two-argument constructor
32 } // end class NegativeNumberException
33 } // end namespace SquareRootTest
Outline
Constructor with two arguments (the Message and InnerException).
NegativeNumberException.cs
( 2 of 2 )
Constructor with a single argument (the Message).
2009 Pearson Education, Inc. All rights reserved.
72
Outline
SquareRootTest.cs
( 4 of 4 ) a) Calculating an integer square root
c) Attempting a negative square root d) Error message displayed
b) Calculating a double square root
• Class SquareRootForm (Fig. 13.7 – next slide) demonstrates using our user-defined exception class
• Its expected input/output behavior:
2009 Pearson Education, Inc. All rights reserved.
73
1 // Fig. 13.7: SquareRootTest.cs
2 // Demonstrating a user-defined exception class.
3 using System;
4 using System.Windows.Forms;
5
6 namespace SquareRootTest
7 {
8 public partial class SquareRootForm : Form
9 {
10 public SquareRootForm()
11 {
12 InitializeComponent();
13 } // end constructor
14
Outline
SquareRootTest.cs
( 1 of 4 )
2009 Pearson Education, Inc. All rights reserved.
74
15 // computes square root of parameter; throws
16 // NegativeNumberException if parameter is negative
17 public double SquareRoot( double value )
18 {
19 // if negative operand, throw NegativeNumberException
20 if ( value < 0 )
21 throw new NegativeNumberException(
22 "Square root of negative number not permitted" );
23 else
24 return Math.Sqrt( value ); // compute square root
25 } // end method SquareRoot
26
27 // obtain user input, convert to double, calculate square root
28 private void squareRootButton_Click( object sender, EventArgs e )
29 {
30 outputLabel.Text = ""; // clear OutputLabel
31
32 // catch any NegativeNumberException thrown
33 try
34 {
35 double result =
36 SquareRoot( Convert.ToDouble( inputTextBox.Text ) );
37
Outline
SquareRootTest.cs
( 2 of 4 )
If the numeric value that the user enters is negative, SquareRoot throws a NegativeNumber-Exception.
SquareRoot invokes Math’s Sqrt method.
Fig. 13.7 | Demonstrating a user-defined exception class. (Part 2 of 4.)
2009 Pearson Education, Inc. All rights reserved.
75
38 outputLabel.Text = result.ToString();
39 } // end try
40 catch ( FormatException formatExceptionParameter )
41 {
42 MessageBox.Show( formatExceptionParameter.Message,
43 "Invalid Number Format", MessageBoxButtons.OK,
44 MessageBoxIcon.Error );
45 } // end catch
46 catch ( NegativeNumberException
47 negativeNumberExceptionParameter )
48 {
49 MessageBox.Show( negativeNumberExceptionParameter.Message,
50 "Invalid Operation", MessageBoxButtons.OK,
51 MessageBoxIcon.Error );
52 } // end catch
53 } // end method squareRootButton_Click
54 } // end class SquareRootForm
55 } // end namespace SquareRootTest
Outline
SquareRootTest.cs
( 3 of 4 )
Catching and handling a NegativeNumber Exception.
Fig. 13.7 | Demonstrating a user-defined exception class. (Part 3 of 4.)
2009 Pearson Education, Inc. All rights reserved.
76
Outline
SquareRootTest.cs
( 4 of 4 )
a) Calculating an integer square root
c) Attempting a negative square root d) Error message displayed
b) Calculating a double square root
Fig. 13.7 | Demonstrating a user-defined exception class. (Part 4 of 4.)
2009 Pearson Education, Inc. All rights reserved.
77
Good Programming Practice 13.1
Associating each type of malfunction with an appropriately named exception class improves program clarity
Software Engineering Observation 13.3
Before creating a user-defined exception class, investigate the existing exceptions in the .NET Framework Class Library to determine whether an appropriate exception type already exists
++READ LATER++ 13.8 User-Defined Exception Classes (Cont.)
2009 Pearson Education, Inc. All rights reserved.
80** SKIP **11.8 (ed.1) Handling Overflows with Operators checked and unchecked
• In .NET, primitive data types are stored in fixed-size structure- E.g.: max. for int is 2,147,483,647 (32 bits, see p.196)
• Trying to assign a value > max. value causes overflow- Overflow causes program to produce incorrect result
• Explicit conversions between integral data types can cause overflow
• C# provides operators checked and unchecked to specify the validity of integer arithmetic (or to specify a fix for an invalid result)
-Checked context- The CLR throws an overflowException if overflow occur during
calculation-Unchecked context- The result of the overflow is truncated
2009 Pearson Education, Inc. All rights reserved.
81
• Use a checked context when performing calculations that can result in overflow- Define exception handlers to process exception caused by overflow
• Example - below
** SKIP **11.8 Handling Overflows with Operators checked and unchecked
2009 Pearson Education, Inc. All rights reserved.
82
Overflow.cs
1 ** SKIP this slide ** // Fig 11.6: Overflow.cs2 // Demonstrating operators checked and unchecked.3 4 using System;5 6 // demonstrates using the checked and unchecked operators7 class Overflow8 {9 static void Main( string[] args )10 {11 int number1 = Int32.MaxValue; // 2,147,483,64712 int number2 = Int32.MaxValue; // 2,147,483,64713 int sum = 0;14 15 Console.WriteLine( 16 "number1: {0}\nnumber2: {1}", number1, number2 );17 18 // calculate sum of number1 and number219 try20 {21 Console.WriteLine( 22 "\nSum integers in checked context:" );23 24 sum = checked( number1 + number2 );25 }26 27 // catch overflow exception28 catch ( OverflowException overflowException )29 {30 Console.WriteLine( overflowException.ToString() );31 }32 33 Console.WriteLine( 34 "\nsum after checked operation: {0}", sum );35
Initialize and declare variables and assigned value to the maximum of int
Sum adds number1 and number2 in a checked context
Number1 and Number2 together causes an overflow, causes overflowException
The catch handler gets the overflowException and prints out its string representation
2009 Pearson Education, Inc. All rights reserved.
83
Overflow.cs
Program Output
36 ** SKIP this slide ** Console.WriteLine( 37 "\nSum integers in unchecked context:" );38 39 sum = unchecked( number1 + number2 );40 41 Console.WriteLine( 42 "sum after unchecked operation: {0}", sum );43 44 } // end method Main45 46 } // end class Overflow
number1: 2147483647
number2: 2147483647
Sum integers in checked context:
System.OverflowException: Arithmetic operation resulted in an overflow.
at Overflow.Overflow.Main(String[] args) in
f:\books\2001\csphtp1\csphtp1_examples\ch11\fig11_09\ overflow\overflow.cs:line 24
sum after checked operation: 0
Sum integers in unchecked context:
sum after unchecked operation: -2
Addition of number1 and number2 in unchecked context
Sum of the numbers in an unchecked context (bec. the overflowing part is truncated)
top related