Você está na página 1de 10

HaNoi University of Technology

Week 8: Exception Handling C# 2008

Week 8: Exception Handling

Contents
Part 1: Part 2: Review Questions (10 Exercises) Programming Questions (3 Exercises)

Concept review
Keywords o Try: include codes in which exceptions might occur o Catch: represent types of exceptions the catch can handle o Finally: (optional) codes present here will always execute ApplicationException o Programmer use to create data types specific to their application o Low chance of program stopping execution SystemException o CLR can generate at any point during execution o Runtime exceptin o Example: IndexOutOfRangeException

1/10

HaNoi University of Technology

Week 8: Exception Handling C# 2008

Part 1:
Exercise 1.

Review Questions

1. True or false: exceptions may be generated by the runtime or by user-defined code. True False 2. Which construct is used to handle exceptions that might be raised within a certain section of code? try/catch try/finally 3. Which construct is used to ensure that a certain section of code always runs whenever execution leaves a designated piece of code, whether due to an exception or not? try/catch try/finally 4. True or false: more than one catch handler can be specified for the same try block. True False 5. True or false: the catch and finally constructs may be associated with the same try block. True False 6. True or false: the CLR allows custom exceptions to be defined. True False

Exercise 2 Which, if any, of the following throw expressions are errors? Why? For the valid throw expressions, indicate the type of the exception thrown.
A. B. C. D.

class exceptionType { }; throw exceptionType(); int excpObj; throw excpObj; enum mathErr { overflow, underflow, zeroDivide }; throw zeroDivide(); int *pi = &excpObj; throw pi;
2/10

HaNoi University of Technology

Week 8: Exception Handling C# 2008

Exercise 3 Given the following exception declarations, provide a throw expression that creates an exception object that can be caught by the following catch clauses.
A. B. C. D.

class exceptionType { }; catch( exceptionType *pet ) { } catch(...) { } enum mathErr { overflow, underflow, zeroDivide }; catch( mathErr &ref ) { } typedef int EXCPTYPE; catch( EXCPTYPE ) { }

Exercise 4 Which one, if any, of the following pointer assignments is in error? Why? void example() throw(string); void (*pf1)() = example; void (*pf2)() throw() = example;

A. B.

Exercise 5 Consider the following exception handling: try {n = v.elementAt(6); i = Arrays.find(z,n);} catch(IndexOutOfBoundsException e){ //handle the exception System.out.println(e.toString()); } 1 1. What is the problem of the above exception handling? 2. Suggest a better exception handling to the above exception case. Exercise 6 Consider the following spesification for PurchaseOrder: class PurchaseOrder { public static final double ERR_CODE1 = -1.0; public double calcItemTotal(double unitPrice, int quantity) { //REQUIRES: quantity > 0 //EFFECTS : If quantity <= 0 then return ERR_CODE1 else // return unitPrice*quantity
3/10

HaNoi University of Technology

Week 8: Exception Handling C# 2008

} } Answer the following questions: 1. What are the problems of the above implementation to detect the exception? 2. Explain briefly how you can modify the above specification to show a better exception detection and handling. 3. Rewrite the specification and code implementation according to your suggestion in question 2.

Exercise 7 Explain what happens during stack unwinding.

Exercise 8 Give two reasons that the exception declaration of a catch clause should declare a reference.

Exercise 9 What exceptions can a function throw if it has an exception specification of the form throw()? If it has no exception specification?

Exercise 10 1. The finally block is generally placed after the try...catch block. Why it is used? What is the difference between the regular code after the try...catch block and code in the finally block. static void Main() { try { // some code } catch(InvalidArgumentException e)
4/10

HaNoi University of Technology

Week 8: Exception Handling C# 2008

{ // some code } finally { // code in finally block } //some regular code } 2. Why should we define our own custom exceptions? What will be the difference if instead of throwing the custom InvalidArgumentException we throw an Exception class object in the Divide() method, e.g. throw new Exception("The second argument of Divide is found zero"); 3. Why do we need multiple catch blocks when we can catch all the exceptions using the base class exception (Exception)?

5/10

HaNoi University of Technology

Week 8: Exception Handling C# 2008

Part 2:
Exercise 11

Programming Questions

Write an applet that catches all Exception objects and displays the string returned by the Exception object's getMessage() method. (Not all Exception objects return message strings. Test your program by generating a divide-byzero error. This exception does generate a message string.).

Figure 1 : ExceptionApplet4 displays the message string returned by an Exception object's getMessage() method.

Exercise 12 Write an applet that enables the user to enter values into an array. Use two TextField objects, the first being where the user shouldenter the index at which to place the value, and the second being the value to add to the array. Set up the applet so that it responds to ArrayIndexOutOfBoundsException and NumberFormatException exceptions.

Figure 2 : This is ExceptionApplet5 running under Appletviewer.

6/10

HaNoi University of Technology

Week 8: Exception Handling C# 2008

Exercise 13 Consider the following code: using System; class ExceptionDemo{ public static void Main(){ int[] table = new int[6]{10,11,12,13,14,15}; int idx = 6; Console.WriteLine("Main"); try{ M(table, idx); } catch (IndexOutOfRangeException){ M(table, AdjustIndex(idx,0,5)); } } public static void M(int[] table, int idx){ Console.WriteLine("M(table,{0})", idx); N(table,idx); } public static void N(int[] table, int idx){ Console.WriteLine("N(table,{0})", idx); P(table,idx); } public static void P(int[] table, int idx){ Console.WriteLine("P(table,{0})", idx); Console.WriteLine("Accessing element {0}: {1}", idx, table[idx]); } public static int AdjustIndex(int i, int low, int high){ int res; if (i < low) res = low; else if (i > high) res = high; else res = i;
7/10

HaNoi University of Technology

Week 8: Exception Handling C# 2008

return res; } } Output Programe Main M(table,6) N(table,6) P(table,6) M(table,5) N(table,5) P(table,5) Accessing element 5: 15 Revise the program with handlers in M, N, and P that touch the exception without actually handling it. The handlers should reveal, on standard output, that P, N, and M are passed in an attempt to locate a relevant exception handler. Rethrow the exception in each case.

8/10

HaNoi University of Technology

Week 8: Exception Handling C# 2008

9/10

HaNoi University of Technology

Week 8: Exception Handling C# 2008

LAB 2: HOMEWORK
Basic try-catch
Create a class called ExceptionTest and add a Main method. Allocate an array of 10 integers and attempt to assign a value into the array using an invalid index. Place the array access in a try block and place a catch block for an IndexOutOfRangeException after the try. Put a print statement in the catch block so you can verify that the handler code is being executed. Compile and run your program and observe the behavior.

10/10

Você também pode gostar