Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exceptions Briana B. Morrison CSE 1302C Spring 2010.

Similar presentations


Presentation on theme: "Exceptions Briana B. Morrison CSE 1302C Spring 2010."— Presentation transcript:

1 Exceptions Briana B. Morrison CSE 1302C Spring 2010

2 2 CSE 1302C Topics Exception Handling –Using try and catch Blocks –Catching Multiple Exceptions –User-Defined Exceptions

3 3 CSE 1302C Exceptions Illegal operations at run time can generate an exception, for example: –ArrayIndexOutOfBoundsException –ArithmeticException –NullPointerException –InputMismatchException –NumberFormatException

4 4 CSE 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

5 5 CSE 1302C Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

6 6 CSE 1302C Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7 7 CSE 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

8 8 CSE 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

9 9 CSE 1302C Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

10 10 CSE 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.

11 11 CSE 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

12 12 CSE 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.

13 13 CSE 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”); }

14 14 CSE 1302C Output In try block… before calling s.ToLower() In catch block… NullReferenceException Caught After try…catch block

15 15 CSE 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

16 16 CSE 1302C ExceptionApplicationExceptionSystemExceptionIndexOutOfRangeExceptionOutOfMemoryExceptionIO.IOExceptionIO.FIleNotFoundExceptionFormatException

17 17 CSE 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.

18 18 CSE 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"); }

19 19 CSE 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.

20 20 CSE 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.

21 21 CSE 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.

22 22 CSE 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

23 23 CSE 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.

24 24 CSE 1302C Full try/catch/finally Syntax try { // 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 }

25 25 CSE 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.

26 26 CSE 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) { }

27 27 CSE 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

28 28 CSE 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.

29 29 CSE 1302C Example 11.6 public 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( ) ); }

30 30 CSE 1302C Questions?


Download ppt "Exceptions Briana B. Morrison CSE 1302C Spring 2010."

Similar presentations


Ads by Google