Upload
omarion-clementson
View
220
Download
0
Tags:
Embed Size (px)
Citation preview
Exceptions
Briana B. MorrisonCSE 1302C
Spring 2010
2CSE 1302C
Topics• Exception Handling
– Using try and catch Blocks– Catching Multiple Exceptions– User-Defined Exceptions
3CSE 1302C
Exceptions• Illegal operations at run time can
generate an exception, for example:– ArrayIndexOutOfBoundsException– ArithmeticException– NullPointerException– InputMismatchException– NumberFormatException
4CSE 1302C
Exceptions• An exception is an object that describes an unusual
or erroneous situation
• Exceptions are thrown by a program, and may be caught and handled by another part of the program
• A program can be separated into a normal execution flow and an exception execution flow
• An error is also represented as an object in C#, but usually represents a unrecoverable situation and should not be caught
5CSE 1302C
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
6CSE 1302C
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
7CSE 1302C
Exception Handling• C# has a predefined set of exceptions and
errors that can occur during execution
• A program can deal with an exception in one of three ways:
– ignore it– handle it where it occurs– handle it an another place in the program
• The manner in which an exception is processed is an important design consideration
8CSE 1302C
Exception Handling
• If an exception is ignored by the program, the program will terminate abnormally and produce an appropriate message
• The message includes a call stack trace that:
– indicates the line on which the exception occurred
– shows the method call trail that lead to the attempted execution of the offending line
9CSE 1302C
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-
Wesley
10CSE 1302C
Handling Exceptions• We don't want invalid user input to
terminate the program! • It is better to detect the problem and
reprompt the user for the input.• We can intercept and handle some of these
exceptions using try and catch blocks.– Inside the try block, we put the code that might
generate an exception.– Inside catch blocks, we put the code to handle any
exceptions that could be generated.
11CSE 1302C
The try Statement• To handle an exception in a program, the line that
throws the exception is executed within a try block
• A try block is followed by one or more catch clauses
• Each catch clause has an associated exception type and is called an exception handler
• When an exception occurs, processing continues at the first catch clause that matches the exception type
12CSE 1302C
Minimum try/catch Syntax try { // code that might generate an exception } catch( ExceptionClass exceptionObjRef ) { // code to recover from the exception }
• If an exception occurs in the try block, the try block terminates and control jumps immediately to the catch block.
• If no exceptions are generated in the try block, the catch block is not executed.
13CSE 1302C
static void Main()
{
string s = null;
try
{
Console.WriteLine(“In try block… before calling s.ToLower()”);
Console.WriteLine(s.ToLower());
Console.WriteLine(“In try block… after calling s.ToLower()”);
}
catch (NullReferenceException e)
{
Console.WriteLine (“In catch block…”);
Console.WriteLine(“NullReferenceException caught”);
}
Console.WriteLine(“After try…catch block”);
}
14CSE 1302C
OutputIn try block… before calling s.ToLower()
In catch block…NullReferenceException CaughtAfter try…catch block
15CSE 1302C
The Exception Class Hierarchy• Classes that define exceptions are related by
inheritance, forming an exception class hierarchy
• All error and exception classes are descendents of the Exception class
• A programmer can define an exception by extending the Exception class or one of its descendants
• The parent class used depends on how the new exception will be used
16CSE 1302C
• Exception
• ApplicationException • SystemException
• IndexOutOfRangeException
• OutOfMemoryException • IO.IOException
• IO.FIleNotFoundException
• FormatException
17CSE 1302C
Recovering From an Exception• The previous code just printed a
message when the exception occurred. • To continue processing and reprompt
the user for good input, we can put the try and catch blocks inside a do/while loop.
18CSE 1302C
public class TryException{
public static void Main(String[] args) {
int value;
bool success = false;
try {
int[] anArray = {5,6,7};
while (! success)
{
int index = int.Parse(args[0]);
value = anArray[index];
Console.WriteLine
("Execution does not get here if index is bad");
success = true;
}
} catch (IndexOutOfRangeException e) {
Console.WriteLine("Stick with 0, 1, or 2");
}
Console.WriteLine("This is the end of the program");
}
}
19CSE 1302C
Software Engineering Tip
Write code to catch and handle exceptions generated by invalid user input.
Although the methods of the Exception class are good debugging tools, they are not necessarily appropriate to use in the final version of a program.
Always try to write code that is user-friendly.
20CSE 1302C
Catching Multiple Exceptions• If the code in the try block might generate
multiple, different exceptions, we can provide multiple catch blocks, one for each possible exception.
• When an exception is generated, the system searches the catch blocks in order. The first catch block with a parameter that matches the exception thrown will execute; any remaining catch blocks will be skipped.
21CSE 1302C
catch Block Order• An exception will match any catch block with
a parameter that names any of its superclasses. – For example, a NumberFormatException will match a
catch block with a SystemException parameter.– All exceptions will match a catch block with an Exception
parameter.
• Thus, when coding several catch blocks, arrange the catch blocks with the specialized exceptions first, followed by more general exceptions.
22CSE 1302C
Exception Propagation• An exception can be handled at a higher level if
it is not appropriate to handle it where it occurs
• Exceptions propagate up through the method calling hierarchy until they are caught and handled or until they reach the level of the Main method
• A try block that contains a call to a method in which an exception is thrown can be used to catch that exception
23CSE 1302C
The finally Block• Optionally, you can follow the catch blocks
with a finally block.• The statements in the finally clause always
are executed• The finally block will be executed whether or
not an exception occurs. Thus:– if an exception occurs, the finally block will be executed
when the appropriate catch block finishes executing– if no exception occurs, the finally block will be executed
when the try block finishes
• For example, a finally block might be used to close an open file. We demonstrate this later.
24CSE 1302C
Full try/catch/finally Syntaxtry{ // code that might generate an exception}catch( Exception1Class e1 ){ // code to handle an Exception1Class exception}… catch( ExceptionNClass eN ){ // code to handle an ExceptionNClass exception} finally{ // code to execute in any case}
25CSE 1302C
Catching Multiple Exceptions• We can write a program that catches
several exceptions. • For example, we can prompt the user for
a divisor. – If the input is not an integer, we catch the
NumberFormatException and reprompt the user with an appropriate message.
– If the input is 0, we catch an SystemException when we attempt to divide by 0, and reprompt the user with an appropriate message.
26CSE 1302C
Extending an Existing Exception• We need to code only the constructor,
which accepts the error message as a string.
• General pattern: public class ExceptionName :
ExistingExceptionClassName { public ExceptionName( string message ) :
base(message) { }
27CSE 1302C
The throw Statement• Exceptions are thrown using the throw
statement
• Usually a throw statement is executed inside an if statement that evaluates a condition to see if the exception should be thrown
28CSE 1302C
Throwing an Exception• The pattern for a method that throws a user-
defined exception is:
accessModifier returnType methodName( parameters ){ if( parameter list is legal ) process the parameter list else
throw new ExceptionName( "Message here" );}
• The message passed to the constructor identifies the error we detected. In a client's catch block, the Message property will retrieve that message.
29CSE 1302C
Example 11.6public class EmailAddress{ public static const char AT_SIGN = '@'; private string email;
public EmailAddress( string newEmail ) { if ( newEmail.indexOf( AT_SIGN ) != - 1 ) email = newEmail; else throw new IllegalEmailException ( "Email address does not contain " + AT_SIGN ); }
public String getHost( ) { int index = email.indexOf( AT_SIGN ); return email.substring( index + 1, email.length( ) ); }}
30CSE 1302C
Questions?