j. goetz, 2012 1 2011 - 13 pearson education, inc. all rights reserved. 2002 prentice hall. all...
TRANSCRIPT
J. Goetz, 2012
1
2011 - 13 Pearson Education, Inc. All rights reserved.
2002 Prentice Hall. All rights reserved.
J. Goetz, 2012
2
It is common sense to take a method and try it. If it fails, admit it frankly and try another. But above all, try something. Franklin Delano Roosevelt
O! throw away the worser part of it,And live the purer with the other half. William Shakespeare
J. Goetz, 2012
3
And oftentimes excusing of a faultDoth make the fault the worse by the excuse. William Shakespeare
If they’re running and they don’t look where they’re going I have to come out from somewhere and catch them. J. D. Salinger
O infinite virtue! com’st thou smiling from the world’s great snare uncaught? William Shakespeare
J. Goetz, 2012
4
Chapter 13 – Exception Handling
Outline13.1 Introduction13.2 Exception Handling Overview13.3 Example: DivideByZeroException13.4 Example: Handling DivideByZeroExceptions and FormatExceptions
13.4.1 Enclosing Code in a try Block 13.4.2 Catching Exceptions 13.4.3 Uncaught Exceptions 13.4.4 Termination Model of Exception Handling 13.4.5 Flow of Control When Exceptions Occur
13.5 .NET Exception Hierarchy13.6 finally Block13.7 Exception Properties13.8 Programmer-Defined Exception Classes Handling Overflows with Operators checked and unchecked
J. Goetz, 2012
5Chapter 13: Exception Handling Objectives
To understand exceptions and error handling. When to use exception handling. To use try blocks to delimit code in which
exceptions may occur. To throw exceptions.
To use catch blocks to specify exception handlers.
To use the finally block to release resources. To understand the C# exception-class hierarchy. To create programmer-defined exceptions.
J. Goetz, 2012
6Error-Prevention Tip 13.1
Exception handling helps improve a program’s fault tolerance.
J. Goetz, 2012
7
Common failures Memory exhaustion Out of bounds array subscript Division by zero Invalid method parameters
Exception An indication of a problem that occurs
during a program’s execution
System.Exception is the base class for all exceptions
13.1 Introduction
J. Goetz, 2012
813.1 Introduction
Errors can be dealt with at place error occurs Easy to see if proper error checking implemented Harder to read application itself and see how code
works
Exception handling Resolving exceptions that may occur so program can
continue or terminate gracefully Create application that can handle or resolve exceptions
Makes clear, robust, fault-tolerant programs
Improves clarity Enhances modifiability
J. Goetz, 2012
9
Exception Handling
Intermixing program logic with error-handling logic can make programs difficult to read, modify, maintain and debug
Enables programmers to remove error-handling code from the “main line” of the program’s execution
13.2 Exception Handling Overview
J. Goetz, 2012
1013.3 Example: Divide By Zero Without Exception Handling
Analyzing the Results Thrown exception
An exception that has occurred
Throw point Initial point at which the exception occurs
DivideByZeroException Occurs when there is a division by zero
FormatException Occurs when the format of an argument does not meet the
parameter specifications of the invoked method
Stack trace Name of the exception in a descriptive message that indicates the
problem
J. Goetz, 2012
11 1 // Fig. 13.1: DivideByZeroNoExceptionHandling.cs
2 // An application that attempts to divide by zero.
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: " ); //dividend
11 int numerator = Convert.ToInt32( Console.ReadLine() );
12 Console.Write( "Please enter an integer denominator: " ); //divisor
13 int denominator = Convert.ToInt32( Console.ReadLine() );
14
15 // divide the two integers, then display the result
16 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
Outline
DivideByZeroNoExceptionHandling.cs
(1 of 2)
J. Goetz, 2012
12
Outline
DivideByZeroNoExceptionHandling.cs
(2 of 2)
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\ch12\Fig12_01\DivideByZeroNoExceptionHandling\ DivideByZeroNoExceptionHandling.cs:line16
Please enter an integer numerator: 100
Please enter an integer denominator: hello
Unhandled Exception: System.FormatException: Attempted to divide by zero. 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\ch12\Fig12_01\DivideByZeroNoExceptionHandling\ DivideByZeroNoExceptionHandling.cs: line13
J. Goetz, 2012
13Exception handling
Exception handling Catch errors before they occur
Deals with synchronous errors (i.e., divide by zero, array out of bounds)
Does not deal with asynchronous (system) errors Disk I/O completions, mouse clicks
Used when system can recover from error
An exception handler - recovery procedure– Is designed to process exceptional conditions –
problems that do not happen frequently, but can happen Useful when program cannot recover but must shut down
cleanly
J. Goetz, 2012
14When Exception Handling Should Be Used
Error handling used for1. Processing exceptional situations
2. Processing exceptions for components that cannot handle them directly
3. Processing exceptions for widely used components (libraries, classes, methods) that should not process their own exceptions
4. Large projects that require uniform error processing
– If a problem occurs at most 30% of the time use exception handling
Remove error-handling code from “main line” of execution
J. Goetz, 2012
15Other Error-Handling Techniques
Other techniques
Ignore exceptions Personal programs usually ignore errors Not for commercial software
Abort upon encountering an exceptional situation- may not release resources Fine for most programs Inappropriate for mission critical programs
J. Goetz, 2012
16Exception Handling Overview
must be in try/catch/finally sequence The try block structure – a watcher for errorstry
{ statements that may throw an exception class object } catch ( ExceptionType exception ) or parameterless catch // catch handler
{ statements to process an exception }
finally { corresponding to try block - always executes (with or without an error) }
J. Goetz, 2012
17Exception Handling Overview!!! must be in try/catch/finally sequence The try block structure – a watcher for errors
try {
statements that may throw an exception class object } // catch handler catch ( ExceptionType exception ) or parameterless catch
{ statements to process an exception }
finally { corresponding to try block - always executes (with or without an error) }
Format and how it works: Enclose code that may have an error in try block
the try block enclosing a thrown exception expires immediately when that exception occurs
Follow with one or more catch blocks Each catch block has an exception handler
If a thrown exception object occurs the CLR searches for the first catch handler that matches parameter in catch block
Code in the catch block executed
– A match occurs if the types are identical or the thrown exception’s type is a derived class of the exception-parameter type
– All remaining catch handlers that correspond to the try block are ignored and execution resumes at the 1st line of code after the try/catch sequence
parameterless catch will catch all exceptions
If no exception thrown Exception handling code skipped Control resumes after catch blocks
J. Goetz, 2012
18Exception Handling Overview
Catch type Must be of class Exception or one that inherits directly or indirectly Single catch can handle multiple exceptions
Exception handling Process synchronous errors Follows the termination model of exception handling
b/c the try block enclosing a thrown exception expires immediately when that exception occurs and
– the local variables defined in the block go out of scope
So program control cannot return to the throw point
Uncaught exceptions yield adverse effects Might terminate program execution
J. Goetz, 2012
19Performance Tips
When no exceptions occur, exception-handling code incurs little or no performance penalties. Thus, programs that implement exception
handling operate more efficiently than programs that perform error handling throughout the program logic.
Exception handling should be used only for problems that occur infrequently. As a "rule of thumb," if a problem occurs at least 30% of the
time when a particular statement executes, the program should test for the error inline (program logic);
otherwise, the overhead of exception handling will cause the program to execute more slowly.
J. Goetz, 2012
2013.3 Example: DivideByZeroException Example program
User enters two integers to be divided We want to catch division by zero errors
Error catching Method Convert.ToInt32 will automatically detect for invalid
representation of an integer
Method Convert.ToInt32 can generates– see online doc.– FormatException value does not consist of an optional sign
followed by a sequence of digits (zero through nine).
– ArgumentException value is a null reference
– OverflowException value represents a number less than MinValue or greater than MaxValue.
CLR automatic detection for division by zero Occurrence will cause a DivideByZeroException
2002 Prentice Hall.All rights reserved.
Outline21
DivideByZeroTest.cs
1 // Fig 13.2: DivideByZeroTest.cs2 // Basics of C# exception handling.3 4 using System;5 using System.Drawing;6 using System.Collections;7 using System.ComponentModel;8 using System.Windows.Forms;9 using System.Data;10 11 // class demonstrates how to handle exceptions from13 // division by zero in integer arithmetic and from 13 // improper numeric formatting14 public class DivideByZeroTest : System.Windows.Forms.Form15 {16 private System.Windows.Forms.Label numeratorLabel;17 private System.Windows.Forms.TextBox numeratorTextBox;18 19 private System.Windows.Forms.Label denominatorLabel;20 private System.Windows.Forms.TextBox denominatorTextBox;21 22 private System.Windows.Forms.Button divideButton;23 private System.Windows.Forms.Label outputLabel;24 25 // required designer variable26 private System.ComponentModel.Container components = null;27 28 // default constructor29 public DivideByZeroTest()30 {31 // required for Windows Form Designer support32 InitializeComponent();33 }34
2002 Prentice Hall.All rights reserved.
Outline22
DivideByZeroTest.cs
35 // main entry point for the application36 [STAThread]37 static void Main() 38 {39 Application.Run( new DivideByZeroTest() );40 } 41 42 // Visual Studio .NET generated code43 44 // obtain integers input by user and divide numerator45 // by denominator46 private void divideButton_Click( 47 object sender, System.EventArgs e )48 {49 outputLabel.Text = "";50 51 // retrieve user input and call Quotient52 try53 {54 // Convert.ToInt32 generates FormatException if 55 // argument is not an integer56 int numerator = Convert.ToInt32( numeratorTextBox.Text );57 int denominator = Convert.ToInt32( denominatorTextBox.Text ); // it may create a FormatException object and throw it to indicate // that the method was unable to convert the string to an int59 60 // division generates DivideByZeroException if61 // denominator is 062 int result = numerator / denominator;63 64 outputLabel.Text = result.ToString();65 66 } // end try67
Try block encloses codes that could result in a throw exception
Will not be reached (executed) if an exception is thrown
DivideByZeroException object thrown if denominator is zero
FormatException object thrown if it cannot convert string into integer
2002 Prentice Hall.All rights reserved.
Outline23
DivideByZeroTest.cs
68 // process invalid number format69 catch ( FormatException ) // in parenthesis a new instance FormatException class is initialized70 {71 MessageBox.Show( "You must enter two integers",72 "Invalid Number Format", 73 MessageBoxButtons.OK, MessageBoxIcon.Error );74 }75 76 // user attempted to divide by zero77 catch ( DivideByZeroException divideByZeroException )78 {79 MessageBox.Show( divideByZeroException.Message,80 "Attempted to Divide by Zero",81 MessageBoxButtons.OK, MessageBoxIcon.Error );82 }83 84 } // end method divideButton_Click85 86 } // end class DivideByZeroTest
Catch handler for FormatException
Catch handler for DivideByZeroException
thrown from the try block
Handler uses property Message of class Exception
When incorrect format are entered into either input fields
Exc: What happens when you comment out either the catch block or both.
Replace line 69 by catch, what happens?
2002 Prentice Hall.All rights reserved.
Outline24
DivideByZeroTest.csProgram Output
When attempting to diving by zero
J. Goetz, 2012
25Software Engineering Observation 13.2
Do not place try blocks around every statement that might throw an exception, because this can make programs difficult to read.
It is better to place one try block around a significant portion of code, and follow this try block with catch blocks that handle each of the possible exceptions.
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.
J. Goetz, 2012
2613.3.1 Enclosing Code in a try Block
try block
Encloses code that might throw an exception and the code that should not execute if an exception occurs
Keyword try followed by a block of code ( { } )
There must be at least one catch block and/or finally block immediately after the try block
try statement Consists of try block and corresponding catch and/or finally
blocks
J. Goetz, 2012
2713.3.2 Catching Exceptions
catch block Catches (i.e., receives) and handles an exception Begins with keyword catch Exception parameter in parentheses
Identifies the exception type and enables catch block to interact with caught exception object
If parameter-less, able to catch all exceptions types Executes when exception of proper type matches
J. Goetz, 2012
2813.3.3 Uncaught Exceptions
Uncaught exception There are no matching catch blocks
Program mostly terminates when there is an uncaught exception If debugging in Visual Studio, application pauses
and Exception Assistant appears indicating where the exception occurred
Throw point Exception Assistant
J. Goetz, 2012
2913.3.4 Termination Model of Exception Handling
When an exception occurs: try block terminates immediately Program control transfers to first matching catch block (other catch block(s) are ignored)
After exception is handled: Termination model of exception handling
Program control does not return to the throw point because the try block has expired
Flow of control proceeds to the first statement after the last catch block
Logic errors can occur if you assume that after an exception is handled, control will return to the first statement after the throw point.
J. Goetz, 2012
3013.4 .NET Exception Hierarchy .Net Framework
Class Exception is base class Derived class:
ApplicationException– Programmers can use to create data types specific to their application– ApplicationException is thrown by a user program, not by the common
language runtime (CLR). – Program can recover from most ApplicationExceptions, low chance of program
stopping execution
SystemException– CLR can generate at any point when it becomes unstable– they called Runtime exception– the program shouldn’t throw or catch SystemException b/c it cannot
recover from most exceptions the CLR throws– Example of a derived class of SystemException
• IndexOutOfRangeException• a null references throw a NullRereferenceException• OutOfMemoryException• StackOverflowException• ExecutionEngineException
J. Goetz, 2012
31Common Programming Error 13.3
It is a compilation 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.
If this were allowed, the base-class catch block would catch all base-class and derived-class exceptions, so the derived-class exception handler would never execute.
J. Goetz, 2012
3213.4.2 Determining Which Exceptions a Method Throws
Methods in the .NET Framework classes Read the online documentations (MSDN) If method throws an exception, its
description contains a section called Exceptions
J. Goetz, 2012
33Exceptions and Inheritance
Inheritance of exception classes Allows polymorphic processing of related exceptions Exception classes can have a common base-class
catch ( Base-class ref ) Catches derived-classes "Is a" relationship
Easier to catch base-class than catching every derived-class
J. Goetz, 2012
34Error-Prevention Tip 13.2
Resource leak occurs since improper allocation of memory we must return resources to prevent it,
specifically for the unclosed files,
“garbage collector” will take care of memory if no more references but
if programmers erroneously keep references to unwanted objects then “garbage collector” doesn’t completely eliminate memory leaks
J. Goetz, 2012
3513.5 Finally Block p.490
finally {block}
Ideal for placing resource release acquired in the corresponding try block e.g. The file when is no longer needed and allocated in the try block.
Execute immediately after catch handler or try block
Always executes whether or not an exception is thrown in the corresponding try block or any of its corresponding catch blocks
Must be present if no catch block is present
Is optional if more than one or more catch handlers exist
J. Goetz, 2012
36Performance 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.
J. Goetz, 2012
37Throw statement
The throw statement is used to signal the occurrence of an anomalous situation (exception) during the program execution.
The throw statement takes the form:
throw [expression]; where: expression
– The exception object– Must be of either class Exception or one of its derived
class– Customize the exception type thrown from methods
The thrown exception is an object whose class is derived from System.Exception, for example:
class MyException : System.Exception {} throw new MyException();
Usually the throw statement is used with try-catch or try-finally statements.
When an exception is thrown, the program looks for the catch statement that handles this exception.
J. Goetz, 2012
38Throw statement
A throw statement can be used in the catch block!!! to rethrow the exception, which has been caught by the catch statement.
For example: catch (InvalidCastException e) { throw (e); // Rethrowing exception e }
Exception Constructors: Initializes a new instance (object) of the Exception class. public: Exception(); Initializes a new instance of the Exception class with a
specified error message. public Exception (string);
This constructor initializes the Message property of the new instance using the message parameter.
2002 Prentice Hall.All rights reserved.
Outline39
1 // Fig 13.4: UsingExceptions.cs2 // Using finally blocks.3 4 using System;5 6 // demonstrating that finally always executes7 class UsingExceptions8 {9 // entry point for application10 static void Main( string[] args )11 {12 // Case 1: No exceptions occur in called method.13 Console.WriteLine( "Calling DoesNotThrowException" );14 DoesNotThrowException();15 16 // Case 2: Exception occurs and is caught 17 // in called method.18 Console.WriteLine( "\nCalling ThrowExceptionWithCatch" );19 ThrowExceptionWithCatch();20 21 // Case 3: Exception occurs, but not caught22 // in called method, because no catch handlers.23 Console.WriteLine( 24 "\nCalling ThrowExceptionWithoutCatch" );25 26 // call ThrowExceptionWithoutCatch27 try 28 {29 ThrowExceptionWithoutCatch();30 }31
UsingExceptions.cs
Static methods of this class so main can invoke directly
Calling DoesNotThrowException 13In DoesNotThrowException 67Finally executed in DoesNotThrowException 80End of DoesNotThrowException 83 case 2:Calling ThrowExceptionWithCatch 18In ThrowExceptionWithCatch 93Message: Exception in ThrowExceptionWithCatch 102Finally executed in ThrowExceptionWithCatch 108End of ThrowExceptionWithCatch 112 case 3:Calling ThrowExceptionWithoutCatch 24In ThrowExceptionWithoutCatch 122Finally executed in ThrowExceptionWithoutCatch 131Caught exception from ThrowExceptionWithoutCatch in Main 37 case 4:Calling ThrowExceptionCatchRethrow 14In ThrowExceptionCatchRethrow 146Message: Exception in ThrowExceptionCatchRethrow 155Finally executed in ThrowExceptionCatchRethrow 166Caught exception from ThrowExceptionCatchRethrow in Main 55
2002 Prentice Hall.All rights reserved.
Outline40
UsingExceptions.cs
32 // process exception returned from 33 // ThrowExceptionWithoutCatch34 catch 35 {36 Console.WriteLine( "Caught exception from " + 37 "ThrowExceptionWithoutCatch in Main" );38 }39 40 // Case 4: Exception occurs and is caught41 // in called method, then rethrown to caller.42 Console.WriteLine( 43 "\nCalling ThrowExceptionCatchRethrow" );44 45 // call ThrowExceptionCatchRethrow46 try // Try block for ThrowExceptionCatchRethrow47 {48 ThrowExceptionCatchRethrow();49 }50 51 // process exception returned from 52 // ThrowExceptionCatchRethrow53 catch54 {55 Console.WriteLine( "Caught exception from " + 56 "ThrowExceptionCatchRethrow in Main" );57 }58 59 } // end method Main60
Another static method of class UsingExceptions
Would process exception that were thrown with no catch handler available
Calling DoesNotThrowException 13In DoesNotThrowException 67Finally executed in DoesNotThrowException 80End of DoesNotThrowException 83 case 2:Calling ThrowExceptionWithCatch 18In ThrowExceptionWithCatch 93Message: Exception in ThrowExceptionWithCatch 102Finally executed in ThrowExceptionWithCatch 108End of ThrowExceptionWithCatch 112 case 3:Calling ThrowExceptionWithoutCatch 24In ThrowExceptionWithoutCatch 122Finally executed in ThrowExceptionWithoutCatch 131Caught exception from ThrowExceptionWithoutCatch in Main 37 case 4:Calling ThrowExceptionCatchRethrow 14In ThrowExceptionCatchRethrow 146Message: Exception in ThrowExceptionCatchRethrow 155Finally executed in ThrowExceptionCatchRethrow 166Caught exception from ThrowExceptionCatchRethrow in Main 55
2002 Prentice Hall.All rights reserved.
Outline41
UsingExceptions.cs
61 // no exceptions thrown – case 162 public static void DoesNotThrowException()63 {64 // try block does not throw any exceptions 65 try 66 {67 Console.WriteLine( "In DoesNotThrowException" );68 }69 70 // this catch never executes71 catch72 {73 Console.WriteLine( "This catch never executes" );74 }75 76 // finally executes because corresponding try executed77 finally78 {79 Console.WriteLine( 80 "Finally executed in DoesNotThrowException" );81 }82 83 Console.WriteLine( "End of DoesNotThrowException" );84 85 } // end method DoesNotThrowException86 87 // throws exception and catches it locally - – case 288 public static void ThrowExceptionWithCatch()89 {90 // try block throws exception91 try 92 {93 Console.WriteLine( "In ThrowExceptionWithCatch" );94
Definition for method DoesNotThrowException( )
Enters the try block, skips catch block and execute the finally block
control returns to Main
Definition for method ThrowExceptionWithCatch( )
Calling DoesNotThrowException 13In DoesNotThrowException 67Finally executed in DoesNotThrowException 80End of DoesNotThrowException 83 case 2:Calling ThrowExceptionWithCatch 18In ThrowExceptionWithCatch 93Message: Exception in ThrowExceptionWithCatch 102Finally executed in ThrowExceptionWithCatch 108End of ThrowExceptionWithCatch 112 case 3:Calling ThrowExceptionWithoutCatch 24In ThrowExceptionWithoutCatch 122Finally executed in ThrowExceptionWithoutCatch 131Caught exception from ThrowExceptionWithoutCatch in Main 37 case 4:Calling ThrowExceptionCatchRethrow 14In ThrowExceptionCatchRethrow 146Message: Exception in ThrowExceptionCatchRethrow 155Finally executed in ThrowExceptionCatchRethrow 166Caught exception from ThrowExceptionCatchRethrow in Main 55
2002 Prentice Hall.All rights reserved.
Outline42
95 throw new Exception( 96 "Exception in ThrowExceptionWithCatch" );97 }98 99 // catch exception thrown in try block100 catch ( Exception error )101 {102 Console.WriteLine( "Message: " + error.Message );103 }104 105 // finally executes because corresponding try executed106 finally107 {108 Console.WriteLine( 109 "Finally executed in ThrowExceptionWithCatch " );110 }111 112 Console.WriteLine( "End of ThrowExceptionWithCatch " );113 114 } // end method ThrowExceptionWithCatch115 § // throws exception and does not catch it locally § – case 3117 public static void ThrowExceptionWithoutCatch()118 {119 // throw exception, but do not catch it120 try 121 {122 Console.WriteLine( "In ThrowExceptionWithoutCatch" );123 124 throw new Exception( 125 "Exception in ThrowExceptionWithoutCatch" );126 }127
The string now becomes the exception object’s error message
Throw statement to throw the exception objectCreate a new Exception object UsingExceptions.
cs
Try block expires because of throw command, program control continue at the first catch following the try block.
Using the exception object’s Message property to access the error message
Try block expires immediately because of “throw new Exception”No catch handlers exist so the program
control go directly to the finally block
Calling DoesNotThrowException 13In DoesNotThrowException 67Finally executed in DoesNotThrowException 80End of DoesNotThrowException 83 case 2:Calling ThrowExceptionWithCatch 18In ThrowExceptionWithCatch 93Message: Exception in ThrowExceptionWithCatch 102Finally executed in ThrowExceptionWithCatch 108End of ThrowExceptionWithCatch 112 case 3:Calling ThrowExceptionWithoutCatch 24In ThrowExceptionWithoutCatch 122Finally executed in ThrowExceptionWithoutCatch 131Caught exception from ThrowExceptionWithoutCatch in Main 37 case 4:Calling ThrowExceptionCatchRethrow 14In ThrowExceptionCatchRethrow 146Message: Exception in ThrowExceptionCatchRethrow 155Finally executed in ThrowExceptionCatchRethrow 166Caught exception from ThrowExceptionCatchRethrow in Main 55
2002 Prentice Hall.All rights reserved.
Outline43
128 // finally executes because corresponding try executed129 finally130 {131 Console.WriteLine( "Finally executed in " +132 " ThrowExceptionWithoutCatch " );133 } // go back and see if the exception can be caught there134 135 // unreachable code; this is within 1st try block line 27136 Console.WriteLine( "This will never be printed" );137 138 } // end method ThrowExceptionWithoutCatch139 140 // throws exception, catches it and rethrows it – case 4141 public static void ThrowExceptionCatchRethrow()142 {143 // try block throws exception144 try 145 { 146 Console.WriteLine( "In ThrowExceptionCatchRethrow" );147 148 throw new Exception( 149 "Exception in ThrowExceptionCatchRethrow" );150 }151 152 // catch any exception, place in object error153 catch ( Exception error )154 {155 Console.WriteLine( "Message: " + error.Message );156 157 // rethrow exception for further processing158 throw error; 159 160 // unreachable code; would generate logic error161 }162
UsingExceptions.cs
Finally block is reached but program control returns to main immediately after
Program control continue from throw statement to the first catch block that match with the same type
Rethrow the exception back to the calling method for further processing, but first the finally block here is executed
Calling DoesNotThrowException 13In DoesNotThrowException 67Finally executed in DoesNotThrowException 80End of DoesNotThrowException 83 case 2:Calling ThrowExceptionWithCatch 18In ThrowExceptionWithCatch 93Message: Exception in ThrowExceptionWithCatch 102Finally executed in ThrowExceptionWithCatch 108End of ThrowExceptionWithCatch 112 case 3:Calling ThrowExceptionWithoutCatch 24In ThrowExceptionWithoutCatch 122Finally executed in ThrowExceptionWithoutCatch 131Caught exception from ThrowExceptionWithoutCatch in Main 37 case 4:Calling ThrowExceptionCatchRethrow 41In ThrowExceptionCatchRethrow 146Message: Exception in ThrowExceptionCatchRethrow 155Finally executed in ThrowExceptionCatchRethrow 166Caught exception from ThrowExceptionCatchRethrow in Main 55
2002 Prentice Hall.All rights reserved.
Outline44
UsingExceptions.cs
Program Output
163 // finally executes because corresponding try executed164 finally 165 {166 Console.WriteLine( "Finally executed in " +167 "ThrowExceptionCatchRethrow" );168 } // go back and see if the exception can be caught there169 170 // unreachable code; this is within 1st try block line 46171 Console.WriteLine( "This will never be printed" );172 173 } // end method ThrowExceptionCatchRethrow174 175 } // end class UsingExceptions
Calling DoesNotThrowException 13In DoesNotThrowException 67Finally executed in DoesNotThrowException 80End of DoesNotThrowException 83 case 2:Calling ThrowExceptionWithCatch 18In ThrowExceptionWithCatch 93Message: Exception in ThrowExceptionWithCatch 102Finally executed in ThrowExceptionWithCatch 108End of ThrowExceptionWithCatch 112
case 3:Calling ThrowExceptionWithoutCatch 24In ThrowExceptionWithoutCatch 122Finally executed in ThrowExceptionWithoutCatch 131Caught exception from ThrowExceptionWithoutCatch in Main 37
case 4:Calling ThrowExceptionCatchRethrow 14In ThrowExceptionCatchRethrow 146Message: Exception in ThrowExceptionCatchRethrow 155Finally executed in ThrowExceptionCatchRethrow 166Caught exception from ThrowExceptionCatchRethrow in Main 55
Finally block reached but program control returns to first occurrence of a try block
J. Goetz, 2012
45Catching an Exception
Catching exceptions Look for the first handler to catch exception All other handlers skipped
If still not caught, non-GUI based applications terminate
try{ try{ throw Exception2 } catch ( Exception1 ){...}
finally {} // executed
// some code which is not executed b/c of throw Exception2
// and this is within 1st try block }catch( Exception2 ){...}
If exception is not caught or if a catch handler rethrows in exception:
•Searches enclosing try catch blocks for appropriate handler ( it may be in the calling method or one of its caller – see previous program)
J. Goetz, 2012
4613.5 finally block (Cont.)
Throwing Exceptions Using the throw statement throw [expression];
where: expression
– The exception object– Must be of either class Exception or one of its
derived class– Customize the exception type thrown from methods
Keyword throw followed by the exception object Programmers can throw exceptions from a method if
something has gone wrong The string passed through the constructor will be the
exception object’s error message– throw new Exception( "Exception in ThrowExceptionCatchRethrow" );
J. Goetz, 2012
47Common 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.
J. Goetz, 2012
4813.5 finally block (Cont.)
Rethrowing Exceptions
Exceptions are rethrown when a catch block decides either that it cannot process the exception or that it can only partially process it
Exception is rethrown by using keyword throw followed by the reference to the exception that was caught
J. Goetz, 2012
4913.5 finally block (Cont.)
Returning After a finally block If the try block successfully completes, or if a catch block
catches and handles an exception The program continues its execution with the next statement
after the finally block
If an exception is not caught, or if a catch block rethrows an exception
Program control continues in the next enclosing try block
– The enclosing try could be in the calling method or in one of its callers
If a try block executes and has a corresponding finally block The finally block executes even if the try block terminates
due to a return statement
J. Goetz, 2012
50Common 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.
Error-Prevention Tip 13.4 When 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.
J. Goetz, 2012
5113.7 Exception Properties
Exception Properties:
Message Stores the error message associated with an Exception object
StackTrace Contains a string that represents the method-
call stack
J. Goetz, 2012
5213.7 Exception Properties
Properties for a exception data types derived from class Exception Message
Stores the error message associated with an Exception object
– May be a default message or customized
public Exception (string);
– This constructor initializes the Message property of the new instance using the message parameter.
StackTrace Contain a string that represents the method call stack Represent sequential list of methods (on stack) that were not fully
processed when the exception occurred
– list of methods that led to the exception The exact location (line #) is called the exception’s throw point
J. Goetz, 2012
5313.7 Exception Properties InnerException property
An instance of Exception that describes the error that caused the current exception. You can create a new exception that catches an earlier exception. The code that
handles the second exception can make use of the additional information from the earlier exception to handle the error more appropriately.
64 catch ( FormatException error ) 65 {66 throw new Exception( "Exception occurred in Method3", error );68 } // object error was caught earlier, error is an inner exception object
returns the same value as was passed into the constructor, or a null reference if the inner exception value was not supplied to the constructor.
“Wrap” exception objects caught in code then throw new exception types that are specific to their libraries
– This property is read-only.
Good Programming Practices 13.6 When 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 and then pass the original caught exception to the new exception object's constructor to initialize the InnerException property.
J. Goetz, 2012
5413.7 Exception Properties
Source property Gets or sets the name of the application or the object that causes the
error If Source is not set, the name of the assembly where the exception originated is
returned.
TargetSite property Gets the method that throws the current exception TargetSite obtains the method from the stack trace. If the stack trace
is a null reference, TargetSite also returns a null reference.
Testing and Debugging Tips When reading a stack trace,
start from the top of the stack trace and read the error message first. Then, read the remainder of the stack trace, looking for the first line that indicates
code that you wrote in your program. Normally, this is the location that caused the exception.
2002 Prentice Hall.All rights reserved.
Outline55
Main becomes first method on the method call stack
Invoked in try block, becomes second on method call stack
Properties.cs
1 // Fig 13.5: Properties.cs2 // Stack unwinding and Exception class properties.3 4 using System;5 6 // demonstrates using the Message, StackTrace and 7 // InnerException properties8 class Properties9 {10 static void Main( string[] args )11 {12 // call Method1, any Exception it generates will be 13 // caught in the catch handler that follows14 try 15 {16 Method1();17 }18 19 // Output string representation of Exception, then20 // output values of InnerException, Message,21 // and StackTrace properties22 catch ( Exception exception ) 23 {24 Console.WriteLine( 25 "exception.ToString(): \n{0}\n",26 exception.ToString() ); // you may omit .ToString()27 28 Console.WriteLine( "exception.Message: \n{0}\n",29 exception.Message );30 31 Console.WriteLine( "exception.StackTrace: \n{0}\n",32 exception.StackTrace );33
When control returns from stack unwinding, try block is expired sending exception to catch block
Catch block uses method ToString and properties Message, StackTrace and InnerException to produce output
exception.ToString():System.Exception: Exception occurred in Method3 ---> System.FormatException: Input string was not in a correct format. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToInt32(String s) at Properties.Method3() in f:\books\2001\csphtp1\csphtp1_examples\ch11\fig11_8\ properties\properties.cs:line 60 --- End of inner exception stack trace --- at Properties.Method3() in f:\books\2001\csphtp1\csphtp1_examples\ch11\fig11_8\ properties\properties.cs:line 66 at Properties.Method2() in f:\books\2001\csphtp1\csphtp1_examples\ch11\fig11_8\ properties\properties.cs:line 51 at Properties.Method1() in f:\books\2001\csphtp1\csphtp1_examples\ch11\fig11_8\ properties\properties.cs:line 45 at Properties.Main(String[] args) in f:\books\2001\csphtp1\csphtp1_examples\ch11\fig11_8\ properties\properties.cs:line 16
2002 Prentice Hall.All rights reserved.
Outline56
34 Console.WriteLine( 35 "exception.InnerException: \n{0}",36 exception.InnerException );37 38 } // end catch39 40 } // end Main41 42 // calls Method243 public static void Method1()44 {45 Method2();46 }47 48 // calls Method349 public static void Method2()50 {51 Method3();52 }53 54 // throws an Exception containing an InnerException55 public static void Method3()56 {57 // attempt to convert non-integer string to int58 try 59 {60 Convert.ToInt32( "Not an integer" );61 }62
Method2 is then unwinds from the method-call stack and return control to Method1
When control return to method2, the CLR determines that there is no try block
Not an integer format, throws a FormatException
Try block uses Convert.ToInt32 which become the fifth and final method on stack
Method3 invoked by Method2 becomes fourth on the method on the stack
Method2 invoked by Method1 becomes third on the method on the stack
Here also, the CLR searches for a try block, but unsuccessful it terminates and unwinds from the call stack
From Method1 control is then returned to the caller which is Main
2002 Prentice Hall.All rights reserved.
Outline57
exception.ToString():System.Exception: Exception occurred in Method3 ---> System.FormatException: Input string was not in a correct format. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToInt32(String s) at Properties.Method3() in f:\books\2001\csphtp1\csphtp1_examples\ch11\fig11_8\ properties\properties.cs:line 60
--- End of inner exception stack trace --- at Properties.Method3() in f:\books\2001\csphtp1\csphtp1_examples\ch11\fig11_8\ properties\properties.cs:line 66 at Properties.Method2() in f:\books\2001\csphtp1\csphtp1_examples\ch11\fig11_8\ properties\properties.cs:line 51 at Properties.Method1() in f:\books\2001\csphtp1\csphtp1_examples\ch11\fig11_8\ properties\properties.cs:line 45 at Properties.Main(String[] args) in f:\books\2001\csphtp1\csphtp1_examples\ch11\fig11_8\ properties\properties.cs:line 16
63 // catch FormatException and wrap it in new Exception64 catch ( FormatException error ) 65 {66 throw new Exception( 67 "Exception occurred in Method3", error ); // error is68 } an inner exception object69 70 } // end method Method371 72 } // end class UsingExceptions
After catch block execute the exception is terminated from the method call stack
Catch handler creates an Exception object, then throws it
First block of output shows the exception’s string representation returned from method ToString
Catches the FormatException thrown by Convert.ToInt32
Properties.cs
Control will be returned to the statement that invoked Method3, which is Method2
Method3 terminates, because the exception thrown is not caught in the method body
The next eight lines show the string representation of the InnerException object
Output for the StackTrace for the Exception thrown in Method3
2002 Prentice Hall.All rights reserved.
Outline58
Properties.csProgram Output
exception.Message:Exception occurred in Method3 exception.StackTrace: at Properties.Method3() in f:\books\2001\csphtp1\csphtp1_examples\ch11\fig11_8\ properties\properties.cs:line 66 at Properties.Method2() in f:\books\2001\csphtp1\csphtp1_examples\ch11\fig11_8\ properties\properties.cs:line 51 at Properties.Method1() in f:\books\2001\csphtp1\csphtp1_examples\ch11\fig11_8\ properties\properties.cs:line 45 at Properties.Main(String[] args) in f:\books\2001\csphtp1\csphtp1_examples\ch11\fig11_8\ properties\properties.cs:line 16 exception.InnerException:System.FormatException: Input string was not in a correct format. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToInt32(String s) at Properties.Method3() in f:\books\2001\csphtp1\csphtp1_examples\ch11\fig11_8\ properties\properties.cs:line 60
These two line represent the Message property of the exception thrown in Method3
StackTrace property of the exception thrown in Method3
- the same as above
ToString representation of the InnerException property
J. Goetz, 2012
5913.8 Programmer-Defined Exception Classes
Creating customized exception types
1. Should derive directly/indirectly from class ApplicationException of namespace System
2. Should have a class that ends with “Exception”
3. Should define three constructors1. A default constructor
2. A constructor that receives a string argument (error msg)
3. A constructor that takes a string argument and an Exception argument (error msg and the inner-exception object)
J. Goetz, 2012
60Software Engineering Observations
Before creating programmer-defined exception classes, investigate the existing exception classes in
the .NET Framework to determine whether an appropriate exception type already exists.
Programmers should create exception classes only if they need to catch and handle the new
exceptions differently from other existing exception types.
2002 Prentice Hall.All rights reserved.
Outline61
NegativeNumberException.cs
1 // Fig 13:6: NegativeNumberException.cs2 // a program defined exception class representing exception2 // NegativeNumberException represents exceptions caused by illegal3 // operations performed on negative numbers4 5 using System;6 7 // NegativeNumberException represents exceptions caused by8 // illegal operations performed on negative numbers9 class NegativeNumberException : ApplicationException10 {11 // default constructor12 public NegativeNumberException()13 : base( "Illegal operation for a negative number" )14 {15 }16 17 // constructor for customizing error message18 public NegativeNumberException( string message )19 : base( message )20 {21 }22 23 // constructor for customizing error message and 24 // specifying inner exception object25 public NegativeNumberException( 26 string message, Exception inner ) 27 : base( message, inner )28 {29 }30 31 } // end class NegativeNumberException
Class NegativeNumberException derives from ApplicationException
This represent the default constructor
This is a constructor that takes in a string argument
This is a constructor that takes in a string argument and an Exception argument: the inner-exception object
J. Goetz, 2012
6213.8 Programmer-Defined Exception Classes
NegativeNumberException ( more likely occur during arithmetic operations) seems logical to derive from ArithmeticException class but ArithmeticException class is thrown by the
CLR which is not for exceptions thrown by the user program
2002 Prentice Hall.All rights reserved.
Outline63
SquareRootTest.cs
1 // Fig 13.6: SquareRootTest.cs2 // Demonstrating a programmer-defined exception class:3 // input a numeric value then calculate the square root of that value4 using System;5 using System.Drawing;6 using System.Collections;7 using System.ComponentModel;8 using System.Windows.Forms;9 using System.Data;10 11 // accepts input and computes the square root of that input12 public class SquareRootTest : System.Windows.Forms.Form13 {14 private System.Windows.Forms.Label inputLabel;15 private System.Windows.Forms.TextBox inputTextBox;16 17 private System.Windows.Forms.Button squareRootButton;18 19 private System.Windows.Forms.Label outputLabel;20 21 // Required designer variable.22 private System.ComponentModel.Container components = null;23 24 // default constructor25 public SquareRootTest()26 {27 // Required for Windows Form Designer support28 InitializeComponent();29 }30 31 // Visual Studio .NET generated code32
2002 Prentice Hall.All rights reserved.
Outline64
SquareRootTest.cs
33 // main entry point for the application34 [STAThread]35 static void Main() 36 {37 Application.Run( new SquareRootTest() );38 } 39 40 // computes the square root of its parameter; throws41 // NegativeNumberException if parameter is negative42 public double SquareRoot( double operand )43 {44 // if negative operand, throw NegativeNumberException45 if ( operand < 0 )46 throw new NegativeNumberException( 47 "Square root of negative number not permitted" );48 49 // compute the square root50 return Math.Sqrt( operand );51 52 } // end class SquareRoot53 54 // obtain user input, convert to double and calculate55 // square root56 private void squareRootButton_Click(57 object sender, System.EventArgs e )58 {59 outputLabel.Text = "";60 61 // catch any NegativeNumberExceptions thrown62 try63 {64 double result = 65 SquareRoot( Double.Parse( inputTextBox.Text ) );66
SqaureRoot throws a NegativeNumberException
Try block invoke SqaureRoot
A FormatException occurs if not a valid number from user
2002 Prentice Hall.All rights reserved.
Outline65
SquareRootTest.cs
67 outputLabel.Text = result.ToString();68 }69 70 // process invalid number format71 catch ( FormatException notInteger )72 {73 MessageBox.Show( notInteger.Message,74 "Invalid Operation", MessageBoxButtons.OK, 75 MessageBoxIcon.Error );76 }77 78 // display MessageBox if negative number input79 catch ( NegativeNumberException error )80 {81 MessageBox.Show( error.Message, "Invalid Operation",82 MessageBoxButtons.OK, MessageBoxIcon.Error );83 }84 85 } // end method squareRootButton_Click86 87 } // end class SquareRootTest
Process the exception caused by FormatException
Catch handler takes care of the NegativeNumberException
Output showing correct function
When attempting to take a negative square root
J. Goetz, 2012
66Handling Overflows with Operators checked and unchecked (no in the
new edition) Calculation that could overflow
Use a checked context when performing calculations that can result in overflow Programmer should define exception handlers to process
the overflow
In .NET, primitive data types are stored in fixed-size structure Example, maximum for int is 2,147,483,647
Overflow causes program to produce incorrect result
C# provides operators checked and unchecked to specify the validity of integer arithmetic.
J. Goetz, 2012
67 Handling Overflows with Operators checked and unchecked
Checked context The CLR throws an overflowException if overflow occur
during calculation
24 sum = checked( number1 + number2 );
Unchecked context The result is of the overflow is truncated
39 sum = unchecked( number1 + number2 );
Explicit conversions between integral data types can cause overflow
2002 Prentice Hall.All rights reserved.
Outline68
Overflow.cs
1 // Fig 11.6 ed1: 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
number1: 2147483647number2: 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
2002 Prentice Hall.All rights reserved.
Outline69
Overflow.cs
Program Output
36 Console.WriteLine( 37 "\nSum integers in unchecked context:" );38 39 sum = unchecked( number1 + number2 ); // the result is //truncated if overflow occurs40 41 Console.WriteLine( 42 "sum after unchecked operation: {0}", sum );43 44 } // end method Main45 46 } // end class Overflow
number1: 2147483647number2: 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
Exc: Remove check or unchecked operators, observe what happens?