#using <System.dll> #using <System.Windows.Forms.dll> using namespace System; using namespace System::Windows::Forms;

Similar documents
Calling predefined. functions (methods) #using <System.dll> #using <System.dll> #using <System.Windows.Forms.dll>

Table 1: Typed vs. Generic Codes Scenario Typed Generic Analogy Cash Only Multiply Payment Options. Customers must pay cash. No cash, no deal.

#using <System.dll> #using <System.Windows.Forms.dll>

Operating System x86 x64 ARM Windows XP Windows Server 2003 Windows Vista Windows Server 2008 Windows 7 Windows Server 2012 R2 Windows 8 Windows 10

However, it is necessary to note that other non-visual-c++ compilers may use:

Question And Answer.

Car. Sedan Truck Pickup SUV

Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation, and definition

public class Animal // superclass { public void run() { MessageBox.Show("Animals can run!"); } }

12/14/2016. Errors. Debugging and Error Handling. Run-Time Errors. Debugging in C# Debugging in C# (continued)

Debugging and Handling Exceptions

CS313D: ADVANCED PROGRAMMING LANGUAGE

accessmodifier [static] returntype functionname(parameters) { } private string getdatetime() { } public void getdatetime() { }

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Basic File Handling and I/O

Exceptions, Case Study-Exception handling in C++.

Object Oriented Programming

#using <System.dll> #using <System.Windows.Forms.dll> using namespace System; using namespace System::Windows::Forms;

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Similarly, example of memory address of array and hash are: ARRAY(0x1a31d44) and HASH(0x80f6c6c) respectively.

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Object Oriented Programming Exception Handling

Object-Oriented Programming

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES

(800) Toll Free (804) Fax Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days

Data Structures. 02 Exception Handling

Std 12 Lesson-10 Exception Handling in Java ( 1

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

C++\CLI. Jim Fawcett CSE687-OnLine Object Oriented Design Summer 2017

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

11Debugging and Handling. C# Programming: From Problem Analysis to Program Design 2nd Edition. David McDonald, Ph.D. Director of Emerging Technologies

Fundamentals of Object Oriented Programming

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

The University of Melbourne Department of Computer Science and Software Engineering Software Design Semester 2, 2003

Data Source. Application. Memory

VALLIAMMAI ENGINEERING COLLEGE

Exceptions. Why Exception Handling?

! Errors can be dealt with at place error occurs

Error Handling. Exceptions

G52CPP C++ Programming Lecture 16

6.Introducing Classes 9. Exceptions

Exceptions. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 15

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Introduction to Programming Using Java (98-388)

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

Course Hours

CS 251 Intermediate Programming Exceptions

Object Oriented Programming

IS 0020 Program Design and Software Tools

BBM 102 Introduction to Programming II Spring Exceptions

ECE 122. Engineering Problem Solving with Java

Lecture 19 Programming Exceptions CSE11 Fall 2013

Absolute C++ Walter Savitch

Programming II (CS300)

Preface to the Second Edition Preface to the First Edition Brief Contents Introduction to C++ p. 1 A Review of Structures p.

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

CS159. Nathan Sprague

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Reminder. Topics CSE What Are Exceptions?! Lecture 11 Exception Handling

BBM 102 Introduction to Programming II Spring 2017

Program Correctness and Efficiency. Chapter 2

Sri Vidya College of Engineering & Technology Question Bank

PROCEDURAL DATABASE PROGRAMMING ( PL/SQL AND T-SQL)

Object-Oriented Programming

Notes on Java Programming IST JAV 2012 S. Frénot

CPSC 427: Object-Oriented Programming

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries

Programming II (CS300)

Exception-Handling Overview

Exception Handling in C++

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Here is a hierarchy of classes to deal with Input and Output streams.

CSC 1214: Object-Oriented Programming

Java Errors and Exceptions. Because Murphy s Law never fails

Microsoft Visual C# Step by Step. John Sharp

CS 11 java track: lecture 3

PROGRAMMING IN VISUAL BASIC WITH MICROSOFT VISUAL STUDIO Course: 10550A; Duration: 5 Days; Instructor-led

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

9. Java Errors and Exceptions

04-24/26 Discussion Notes

CPSC 427: Object-Oriented Programming

Problem Solving with C++

Software Design and Analysis for Engineers

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Exceptions. Text: Chapter19, Big C++

Learning to Program in Visual Basic 2005 Table of Contents

CSC 330 Object-Oriented Programming. Exception Handling CSC 330

Sahaj Computer Solutions OOPS WITH C++

Exception handling. Aishy Amer. Lecture Outline: Introduction Types or errors or exceptions Conventional error processing Exception handling in C++

Chapter 11: Exception Handling

Microsoft. Microsoft Visual C# Step by Step. John Sharp

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

4.3 FURTHER PROGRAMMING

5 When a program calls a function, in which type of data structure is memory allocated for the variables in that function?

Exception Handling. Chapter 11. Outline. Example: The Quotient app What Are Exceptions? Java By Abstraction Chapter 11

Laboratorio di Tecnologie dell'informazione

Transcription:

Lecture #13 Introduction Exception Handling The C++ language provides built-in support for handling anomalous situations, known as exceptions, which may occur during the execution of your program. Exceptions are unexpected but frequently foreseeable errors that happen in your programs. Interestingly, in most of the time, you can possibly detect the program errors in your code. For example, no number can be divided by zero. In the following code, you will hit the situation when denominator (i) is zero. Since the error is now expected, you should try to handle it. for (int i=-4; i<=4; i++) str += (5/i) + " "; MessageBox::Show(str); In the above code, the counter variable i in the for loop will have a chance to equal 0. When i=0, the operation of 5/i will cause an error because nothing can be divided by zero. The above code will cause the following error message during the compilation. Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero... Obviously exceptions are run-time anomalies, such as division by zero, that require immediate handling when encountered by your program. In C++, the process of raising an exception is called throwing an exception. A designated exception handler then catches the thrown exception. In many cases, an exception may be thrown not by a method that your code has called directly, but by another method further down in the call stack. When this happens, the CLR will unwind the stack, looking for a method with a catch block for the specific exception type, and it will execute the first such catch block that if finds. If it finds no appropriate catch block anywhere in the call stack, it will terminate the process and display a message to the user. The following are common exceptions defined by the System namespace. Exception class ArithmeticException ArrayTypeMismatchException DivideByZeroException IndexOutOfRangeException Description A base class for exceptions that occur during arithmetic operations, such as System.DivideByZeroException and System.OverflowException. Thrown when a store into an array fails because the actual type of the stored element is incompatible with the actual type of the array. Thrown when an attempt to divide an integral value by zero occurs. Thrown when an attempt to index an array via an index that is less than zero or outside the bounds of the array. Visual C++ Programming Penn Wu, PhD 348

InvalidCastException NullReferenceException OutOfMemoryException OverflowException StackOverflowException TypeInitializationException Thrown when an explicit conversion from a base type or interface to a derived type fails at run time. Thrown when a null reference is used in a way that causes the referenced object to be required. Thrown when an attempt to allocate memory (via new) fails. Thrown when an arithmetic operation in a checked context overflows. Thrown when the execution stack is exhausted by having too many pending method calls; typically indicative of very deep or unbounded recursion. Thrown when a static constructor throws an exception, and no catch clauses exists to catch it. An arithmetic operation produces a result that is outside the range of the data type returned by the operation. The following example illustrates the OverflowException that is thrown by a multiplication operation that overflows the bounds of the Int36 type. OverflowException is the exception that is thrown when an arithmetic, casting, or conversion operation in a checked context results in an overflow. int value = 999999999; int cube = value * value * value; MessageBox::Show(Convert::ToInt16(cube)+""); The example displays the following output: Unhandled Exception: System.OverflowException: Value was either too large or too small for an Int16. If you modify the source code to following, the problem will go away. This is because the Int64 type support up to 9,223,372,036,854,775,808 which is larger than 999,999,999 3. int value = 999999999; Int64 cube = (Int64) value * (Int64) value * (Int64) value; MessageBox::Show(Convert::ToString(cube)); A sample way to handle this exception with try..catch statement will be: Visual C++ Programming Penn Wu, PhD 349

int value = 999999999; int cube = value * value * value; MessageBox::Show(Convert::ToInt16(cube)+""); catch (OverflowException^ e) Int64 cube = (Int64) value * (Int64) value * (Int64) value; MessageBox::Show(Convert::ToString(cube)); The OutOfMemoryException is triggered by allocation instructions and is thrown by the execution engine; it can occur during any allocation call during runtime, and there are ways to predict the failure. The following is a simple program that raises out-of-memory exception in C#. String^ value = gcnew String('a', Int32::MaxValue); This code raise the following exception: Unhandled Exception: OutOfMemoryException The above program attempts to allocate a string that is extremely large and would occupy four gigabytes of memory. However, the OutOfMemoryException is thrown by the runtime because this is not possible. The intention of the program is to demonstrate the exception itself and not to provide a realistic example. Exception handling may use the try, catch, and finally keywords to handle foreseeable exceptions. A finally block contains code that is run regardless of whether or not an exception is thrown in the try block, such as releasing resources that are allocated in the try block. A try block requires one or more associated catch blocks, or a finally block, or both. C++ exception handling is thread-safe. Throwing on one thread (including re-throw) has no impact on any throw/catch in progress on another thread. The try block A try block is used by C# programmers to partition code that might be affected by an exception. The try block contains the guarded code that may cause the exception. The block is executed until an exception is thrown or it is completed successfully. The associated catch blocks are used to handle any resulting exceptions. The following examples show a generic try-catch statement: // Code to try goes here. Visual C++ Programming Penn Wu, PhD 350

catch (SomeSpecificException^ e) // Code to handle the exception goes here. The following code will cause a NullReferenceException exception because object reference cannot be casted to a type. Object^ o2 = nullptr; int i2 = (int) o2; // Error You can use the following to attempt to cast a null object raises the NullReferenceException exception. NullReferenceException is the exception that is thrown when there is an attempt to dereference a null object reference. Object^ o2 = nullptr; int i2 = (int) o2; // Error You should always specify an object argument derived from System.Exception in the catch clause. For example, although InvalidCastException is an exception that is thrown for invalid casting or explicit conversion, it may not handle the NullReferenceException exception. The following is the sample catch clause that can handle the NullReferenceException exception. The Message property gets a message that describes the current exception. or catch (NullReferenceException^ e) catch (NullReferenceException^ e) msg = e->tostring(); The trick is to pass the exception message from runtime to string variable msg, thus, the error message will not display on the screen and the program will run without interruption. A complete code looks: Object^ o2 = nullptr; int i2 = (int) o2; // Error catch (NullReferenceException^ e) Visual C++ Programming Penn Wu, PhD 351

You can add a try block to handle the above issue (attempting to divide by zero). For example, for (int i = -4; i <= 4; i++) str += (5/i) + " "; catch (Exception^ e) continue; MessageBox::Show(str); The code will first attempt to let 5 divide by the current value of i. The division should go through unless i = 0. When i = 0, the exception happens and this exception will be caught by the catch statement. In the catch statement there is a parameter e declared as Exception type which represents errors that occur during application execution. According to the above code, the error message is assigned to a variable named msg, so it will not bounce to the console screen. The continue statement also forces the run-time to jump to next loop (i=1). With this exception handling mechanism. The above program will run smoothly without any interruption. The error message will not be displayed. A catch block can specify the type of exception to catch. The type specification is called an exception filter. The exception type should be derived from Exception. In general, Microsoft s MSDN site suggest you not to specify Exception as the exception filter unless either you know how to handle all exceptions that might be thrown in the try block, or you have included a throw statement at the end of your catch block. Using the class of exception that is specially designed to handle this type of exception is probably a better way. You can use the more specific System.DivideByZeroExceptione exception which is the exception that is thrown when there is an attempt to divide an integral or decimal value by zero. Simply replace the catch clause of the above with the following. catch (DivideByZeroExceptione^ e) continue; Visual C++ Programming Penn Wu, PhD 352

IndexOutOfRangeException is another frequently seen exception. The exception that is thrown when an attempt is made to access an element of an array with an index that is outside the bounds of the array. This class cannot be inherited. In the following, the x array can only have 5 elements, but the for loop attempts to create 8 elements. int[] x = new int[5]; for (int i=0; i<=7; i++) x[i] = i * i; This code will cause the following error message: Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array... You can handle this exception with a generic try block as shown below. array<int^>^ x = gcnew array<int^>(5); for (int i=0; i<=7; i++) x[i] = i * i; catch(indexoutofrangeexception^ e) continue; A throw statement can be used in a catch block to re-throw the exception that is caught by the catch statement. One of the above catch clauses already handles the exception; however, the throw statement in the following example re-throws the exception again. Object^ o2 = nullptr; int i2 = (int) o2; // Error catch (NullReferenceException^ e) throw; You can catch one exception and throw a different exception. When you do this, specify the exception that you caught as the inner exception, as shown in the following example. catch (NullReferenceException^ e) Visual C++ Programming Penn Wu, PhD 353

throw gcnew InvalidCastException("My customized error message."); Although the catch clause can be used without arguments to catch any type of exception, this usage is not recommended. In general, you should only catch those exceptions that you know how to recover from. Therefore, In the following example, the try block contains a call to the ProcessString method that may cause an exception. The catch clause contains the exception handler that just displays a message on the screen. When the throw statement is called from inside MyMethod, the system looks for the catch statement and displays the message Exception caught. void ProcessString(String^ s) if (s == nullptr) throw gcnew ArgumentNullException(); String^ s = nullptr; // For demonstration purposes. ProcessString(s); catch (Exception^ e) MessageBox::Show(e->ToString()); The output in the console is: System.ArgumentNullException: Value cannot be null. at TryFinallyTest.Main() Exception caught. a try-catchfinally statement A finally block enables you to clean up actions that are performed in a try block. If present, the finally block executes last, after the try block and any matched catch block. A finally block always runs, regardless of whether an exception is thrown or a catch block matching the exception type is found. A generic format in C# looks: For example, // Code to try goes here. catch (SomeSpecificException^ e) // Code to handle the exception goes here. finally // Code to execute after the try block goes here. Visual C++ Programming Penn Wu, PhD 354

for (int i = -4; i <= 4; i++) str += (5/i) + " "; catch (Exception^ e) continue; finally if (i == 0) str += " NaN "; MessageBox::Show(str); The final statement defines what to display when i = 0, which is NaN. The output looks: Another example is: array<int^>^ x = gcnew array<int^>(5); for (int i=0; i<=7; i++) x[i] = i * i; catch(indexoutofrangeexception^ e) continue; finally if (i< x->length) // the Length property str += x[i] + " "; Visual C++ Programming Penn Wu, PhD 355

MessageBox::Show(str); It is possible to use more than one specific catch clause in the same try-catch statement. In this case, the order of the catch clauses is important because the catch clauses are examined in order. Catch the more specific exceptions before the less specific ones. The compiler produces an error if you order your catch blocks so that a later block can never be reached. In this example, two catch statements are used. The most specific exception, which comes first, is caught. void ProcessString(String^ s) if (s == nullptr) throw gcnew ArgumentNullException(); String^ s = nullptr; // For demonstration purposes. ProcessString(s); // Most specific: catch (ArgumentNullException^ e) MessageBox::Show(e->ToString()); // Least specific: catch (Exception^ e) MessageBox::Show(e->ToString()); The finally block can be used to release resources such as file streams, database connections, and graphics handles without waiting for the garbage collector in the runtime to finalize the objects. The following example, the finally block is used to close a file that is opened in the try block. Notice that the state of the file handle is checked before the file is closed. If the try block cannot open the file, the file handle still has the value null and the finally block does not try to close it. Alternatively, if the file is opened successfully in the try block, the finally block closes the open file. using namespace System::IO; FileStream^ file = nullptr; FileInfo^ fileinfo = gcnew FileInfo("C:\\file.txt"); file = fileinfo->openwrite(); Visual C++ Programming Penn Wu, PhD 356

file->writebyte(0xf); finally // Check for null because OpenWrite might have failed. if (file!= nullptr) file->close(); Question 1. Given the following code segment, what possible exception will it throw? for (int i = -4; i <= 4; i++) str += (5/i) + " "; A. ArithmeticException B. OverflowException C. IndexOutOfRangeException D. DivideByZeroException 2. Given the following code segment, what possible exception will it throw? int value = 987654321; int cube = value * value * value; MessageBox::Show(Convert::ToInt16(cube)+""); A. ArithmeticException B. OverflowException C. IndexOutOfRangeException D. DivideByZeroException 3. Given the following code segment, what possible exception will it throw? String^ value = gcnew String('a', Int32::MaxValue); A. OutOfMemoryException B. OverflowException C. StackOverflowException D. TypeInitializationException 4. Given the following code, which can display the error in a message box when exception happens? catch (NullReferenceException^ e)... A. e->messagebox::show(); B. MessageBox::Show(e); C. MessageBox::Show(Message(e)); D. MessageBox::Show(e->ToString()); 5. Given the following code segment, what possible exception will it throw? array<int^>^ x = gcnew array<int^>(5); for (int i=0; i<=7; i++) x[i] = i * i; Visual C++ Programming Penn Wu, PhD 357

A. ArithmeticException B. OverflowException C. IndexOutOfRangeException D. DivideByZeroException 6. How many times will the following catch statement display the error message on screen? A. 1 B. 2 C. 3 D. 4 catch (NullReferenceException^ e) throw; 7. Which statement is correct? A. A finally block enables you to clean up actions that are performed in a try block. B. If present, the finally block executes last, after the try block and any matched catch block. C. A finally block always runs, regardless of whether an exception is thrown or a catch block matching the exception type is found. D. The NullReferenceException constant does not have any affect in this case. 8. Given the following code, which statement is incorrect? array<int^>^ x = gcnew array<int^>(5); for (int i=0; i<=7; i++) x[i] = i; str += x[i] + " "; catch(indexoutofrangeexception) if (i>= x->length) continue; MessageBox::Show(str); A. The x array has 5 elements. B. The for loop will executes 8 times. C. The result is 0 1 2 3 4. D. The x array does not contain any element. 9. When an ArgumentNullException exception is thrown, which exception will be caught? catch(indexoutofrangeexception^ e) MessageBox::Show("1" + e->tostring()); catch (ArgumentNullException^ e) MessageBox::Show("2" + e->tostring()); catch (Exception^ e) MessageBox::Show("3" + e->tostring()); A. MessageBox::Show("1" + e->tostring()); B. MessageBox::Show("2" + e->tostring()); Visual C++ Programming Penn Wu, PhD 358

C. MessageBox::Show("3" + e->tostring()); D. MessageBox::Show("4" + e->tostring()); 10. The exception is the exception that is thrown when an arithmetic, casting, or conversion operation in a checked context results in an overflow. A. ArithmeticException B. OverflowException C. OutOfMemoryException D. StackOverflowException Visual C++ Programming Penn Wu, PhD 359

Lab #13 Exception Handling Learning Activity #1: 1. Launch the Developer Command Prompt (not the regular Command Prompt) and change to the C:\cis223 directory. 2. Use Notepad to create a new text file named lab13_1.cpp with the following contents: //incorrect int value = 987654321; int cube = Math::Pow(value, 3); // error MessageBox::Show(Convert::ToInt16(cube)+""); 3. Compile and test the program to observe the error message. 4. Re-open the source file and change the source code to the following: // solution String^ str =""; int value = 987654321; double cube = Math::Pow(value, 3); // error MessageBox::Show(Convert::ToInt16(cube)+""); catch (OverflowException^ e) str = e->tostring(); cube = Math::Pow((long) value, 3); MessageBox::Show(cube.ToString()); 5. Type cl /clr lab13_1.cpp /link /subsystem:windows /ENTRY:main and press [Enter] to compile. Test the program. A sample output looks: Visual C++ Programming Penn Wu, PhD 360

6. Download the assignment template, and rename it to lab13.doc if necessary. Capture a screen shot similar to the above figure and paste it to the Word document named lab13.doc (or.docx). Learning Activity #2: 1. Use Notepad to create a new text file named lab13_2.cpp with the following contents: //incorrect for (int i = -4; i <= 4; i++) str += (5/i) + " "; MessageBox::Show(str); 2. Compile and test the program to observe the error message. 3. Re-open the source file and change the source code to the following: for (int i = -4; i <= 4; i++) str += (5/i) + " "; catch (Exception^ e) continue; finally if (i==0) str += " NaN "; MessageBox::Show(str); 4. Compile and test the program. A sample output looks: Visual C++ Programming Penn Wu, PhD 361

5. Capture a screen shot similar to the above figure and paste it to the Word document named lab13.doc (or.docx). Learning Activity #3: 1. Use Notepad to create a new text file named lab13_3.cpp with the following contents: //Incorrect array<int^>^ x = gcnew array<int^>(5); for (int i=0; i<=7; i++) x[i] = i * i; for (int i=0; i<x->length; i++) str += x[i] + " "; MessageBox::Show(str); 2. Compile and test the program to observe the error message. 3. Re-open the source file and change the source code to the following: array<int^>^ x = gcnew array<int^>(5); for (int i=0; i<=7; i++) x[i] = i * i; catch(indexoutofrangeexception^ e) continue; finally if (i<x->length) // the Length property str += x[i] + " "; Visual C++ Programming Penn Wu, PhD 362

str += "\nthe number of element is " + x->length + "\n"; for (int i=0; i<x->length; i++) str += x[i] + " "; MessageBox::Show(str); 4. Compile and test the program. A sample output looks: 5. Capture a screen shot similar to the above figure and paste it to the Word document named lab13.doc (or.docx). Learning Activity #4: OutOfMemoryException 1. Use Notepad to create a new text file named lab13_4.cpp with the following contents: array<int^>^ LargeArray = gcnew array<int^>(987654321); for (int i=0; i<largearray->length; i++) LargeArray[i] = i; MessageBox::Show("The last element is " + LargeArray[LargeArray->Length - 1]); 2. Compile and test the program to observe the error message. 3. Re-open the source file and change the source code to the following: array<int^>^ LargeArray; LargeArray = gcnew array<int^>(987654321); catch(outofmemoryexception^ e) msg = e->tostring(); Visual C++ Programming Penn Wu, PhD 363

// set the Length to the largest possible value of an Int16. LargeArray = gcnew array<int^>(int16::maxvalue); for (int i=0; i<largearray->length; i++) LargeArray[i] = i; MessageBox::Show("The last element is " + LargeArray[LargeArray->Length - 1]); 4. Compile and test the program. A sample output looks: 5. Capture a screen shot similar to the above figure and paste it to the Word document named lab13.doc (or.docx). Learning Activity #5: 1. Make sure the X:\nippon directory DOES NOT exist (where x indicates your system directory). Delete it if it exists. 2. Use Notepad to create a new text file named lab13_5.cpp with the following contents: using namespace System::IO; String^ sdrive = System::Environment::GetEnvironmentVariable("homedrive"); FileStream^ file = nullptr; FileInfo^ fi = gcnew FileInfo(sDrive + "\\nippon\\nagasaki.txt"); file = fi->openwrite(); file->writebyte(0xf); 3. Compile and test the program to observe the error message. 4. Re-open the source file and change the source code to the following: using namespace System::IO; String^ sdrive = System::Environment::GetEnvironmentVariable("homedrive"); FileStream^ file = nullptr; FileInfo^ fi = gcnew FileInfo(sDrive + "\\nippon\\nagasaki.txt"); Visual C++ Programming Penn Wu, PhD 364

file = fi->openwrite(); file->writebyte(0xf); msg = "No error"; catch (DirectoryNotFoundException^ e) msg = e->tostring(); if (!Directory::Exists(sDrive + "\\nippon")) Directory::CreateDirectory(sDrive + "\\nippon"); FileStream^ file = nullptr; FileInfo^ fi = gcnew FileInfo(sDrive + "\\nippon\\nagasaki.txt"); msg = "No such directory or file. But, we just created one. \nnow check the '" + sdrive + "\\nippon' to verify."; finally // Check for null because OpenWrite might have failed. if (file!= nullptr) file->close(); MessageBox::Show(msg); 5. Compile and test the program. The output looks: X:\nippon directory does not exist X:\nippon directory exist 6. Capture a screen shot similar to the above figure and paste it to the Word document named lab13.doc (or.docx). Submittal 1. Complete all the 5 learning activities and the programming exercise in this lab. 2. Create a.zip file named lab13.zip containing ONLY the following self-executable files. lab13_1.exe lab13_2.exe lab13_3.exe lab13_4.exe lab13_5.exe lab13.doc (or lab13.docx or.pdf) [You may be given zero point if this Word document is missing] 3. Log in to Blackboard, and enter the course site. 4. Upload the zipped file to Question 11 of Assignment 10 as response. 5. Upload ex13.zip file to Question 12 as response. Note: You will not receive any credit if you submit file(s) to the wrong question. Programming Exercise 13: 1. Launch the Developer Command Prompt. 2. Use Notepad to create a new text file named ex13.cpp. Visual C++ Programming Penn Wu, PhD 365

3. Add the following heading lines (Be sure to use replace [YourFullNameHere] with the correct one). //File Name: ex13.cpp //Programmer: [YourFullNameHere] int i = 123; String^ s = "Arigatoh"; Object^ o = s; i = (int) o;// Invalid conversion; o contains a string not an int MessageBox::Show(i.ToString()); 4. Add a try-catch statement with an InvalidCastException exception to above code so the following message can be displayed without any error or interrupts. 5. Download the programming exercise template, and rename it to ex13.doc if necessary. Capture Capture a screen similar to the above figures and paste it to the Word document named ex13.doc (or.docx). 6. Compress the source file (ex13.cpp), executable code (ex13.exe), and Word document (ex13.doc) to a.zip file named ex13.zip. Grading criteria: You will earn credit only when the following requirements are fulfilled. No partial credit is given. You successfully submit both source file and executable file. Your program must meet all requirements. Your source code must be fully functional and may not contain syntax errors in order to earn credit. Your executable file (program) must be executable to earn credit. Threaded Discussion Note: Students are required to participate in the thread discussion on a weekly basis. Student must post at least two messages as responses to the question every week. Each message must be posted on a different date. Grading is based on quality of the message. Question: Class, many exceptions or errors can be handled by a nested "if" structure. What is/are the advantage(s) or disadvantage(s) of using the try..catch structure in Visual C++. If you can, provide an example to support your perspective. [There is never a right-or-wrong answer for this question. Please free feel to express your opinion.] Be sure to use proper college level of writing. Do not use texting language. Visual C++ Programming Penn Wu, PhD 366