版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
1、 2009 Pearson Education, Inc. All rights reserved.113ExceptionHandling 2009 Pearson Education, Inc. All rights reserved.2OBJECTIVESIn this chapter you will learn: What exceptions are and how they are handled. When to use exception handling. To use try blocks to delimit code in which exceptions might
2、 occur. To throw exceptions to indicate a problem. To use catch blocks to specify exception handlers. To use the finally block to release resources. The .NET exception class hierarchy. Exception properties. To create user-defined exceptions. 2009 Pearson Education, Inc. All rights reserved.313.1 Int
3、roduction13.2 Exception Handling Overview13.3 Example: Divide by Zero without Exception Handling13.4 Example: Handling DivideByZeroExceptionDivideByZeroExceptions and FormatExceptionFormatExceptions13.5 .NET ExceptionException Hierarchy13.6 finallyfinally Block13.7 ExceptionException Properties13.8
4、User-Defined Exception Classes 2009 Pearson Education, Inc. All rights reserved.413.1 Introduction An exception is an indication of a problem that occurs during a programs execution. Exception handling enables applications to resolve exceptions. Exception handling enables clear, robust and morefault
5、-tolerant programs.Error-Prevention Tip 13.1Exception handling helps improve a programsfault tolerance. 2009 Pearson Education, Inc. All rights reserved.513.2 Exception Handling Overview Consider the following pseudocode:Perform a taskIf the preceding task did not execute correctlyPerform error proc
6、essingPerform next taskIf the preceding task did not execute correctlyPerform error processingIn this pseudocode, we begin by performing a task;then we test whether that task executed correctly.If not, we perform error processing. 2009 Pearson Education, Inc. All rights reserved.613.2 Exception Hand
7、ling Overview (Cont.) Exception handling enables programmers to removeerror-handling code from the “main line” of the programs execution. Programmers can decide to handle all exceptions, all exceptions of a certain type or all exceptions of related types. Such flexibility reduces the likelihood that
8、 errors will be overlooked. 2009 Pearson Education, Inc. All rights reserved.7Fig. 13.1 | Integer division without exception handling. (Part 1 of 3.)OutlineDivideByZeroNoDivideByZeroNoExceptionHandlingExceptionHandling.cs.cs( 1 of 3 ) Figure 13.1s application divides one input integer by a second to
9、 obtain an int result. In this example, well see that an exception is thrown when a method detects a problem.Converting values can cause a FormatException. Converting values can cause a FormatException. 2009 Pearson Education, Inc. All rights reserved.8OutlineDivision can cause a DivideByZeroExcepti
10、on. DivideByZeroNoDivideByZeroNoExceptionHandlingExceptionHandling.cs.cs( 2 of 3 ) Fig. 13.1 | Integer division without exception handling. (Part 2 of 3.) 2009 Pearson Education, Inc. All rights reserved.9OutlineDivideByZeroNoDivideByZeroNoExceptionHandlingExceptionHandling.cs.cs( 3 of 3 ) Fig. 13.1
11、 | Integer division without exception handling. (Part 3 of 3.) 2009 Pearson Education, Inc. All rights reserved.1013.3 Example: Divide by Zero without Exception Handling If you run using Debug Start Debugging, the program pauses at the line where an exception occurs. Try executing the application fr
12、om a Command Prompt window. When an error arises, a dialog indicates that the application has encountered a problem and needs to close. An error message describing the problem is displayed in the Command Prompt. 2009 Pearson Education, Inc. All rights reserved.1113.3 Example: Divide by Zero without
13、Exception Handling (Cont.) Additional informationknown as a stack tracedisplays the exception name and the path of execution that led to the exception. Each “at” line in the stack trace indicates a line of code in the particular method that was executing when the exception occurred. This information
14、 tells where the exception originated, and what method calls were made to get to that point. 2009 Pearson Education, Inc. All rights reserved.1213.3 Example: Divide by Zero without Exception Handling (Cont.) A FormatExceptionFormatException occurs when Convert method ToInt32 receives a string that d
15、oes not represent a valid integer. A program may continue executing even though an exception has occurred and a stack trace has been printed. In such cases, the application may produce incorrect results. 2009 Pearson Education, Inc. All rights reserved.13 This application (Fig. 13.2) uses exception
16、handling to process DivideByZeroExceptions and FormatExceptions. This program demonstrates how to catch and handle (i.e., deal with) such exceptions. OutlineDivideByZeroTestDivideByZeroTest.cs .cs ( 1 of 4 ) Fig. 13.2 | FormatException and DivideByZeroException handlers. (Part 1 of 4.) 2009 Pearson
17、Education, Inc. All rights reserved.14OutlineDivideByZeroTestDivideByZeroTest.cs .cs ( 2 of 4 ) Fig. 13.2 | FormatException and DivideByZeroException handlers. (Part 2 of 4.) 2009 Pearson Education, Inc. All rights reserved.15OutlineDivideByZeroTestDivideByZeroTest.cs .cs ( 3 of 4 ) Fig. 13.2 | Form
18、atException and DivideByZeroException handlers. (Part 3 of 4.)This block catches and handles a FormatException. This block catches and handles a DivideBy-ZeroException. 2009 Pearson Education, Inc. All rights reserved.16Outlinea) Performing integer divisionb) Dividing by zerod) Entering a string val
19、uee) Error messagec) Error messageDivideByZeroTestDivideByZeroTest.cs .cs ( 4 of 4 ) Fig. 13.2 | FormatException and DivideByZeroExceptionhandlers. (Part 3 of 4.) 2009 Pearson Education, Inc. All rights reserved.1713.4 Example: Handling DivideByZeroExceptionsDivideByZeroExceptions and FormatExceptio
20、nsFormatExceptions The Int32.TryParseInt32.TryParse method converts a string to an int value if possible. The method requires two argumentsone is the string to parse and the other is the variable in which the converted value is to be stored. The method returns true if the string was parsed successfu
21、lly. If the string could not be converted, the value 0 is assigned to the second argument. 2009 Pearson Education, Inc. All rights reserved.1813.4 Example: Handling DivideByZeroExceptionsDivideByZeroExceptions and FormatExceptionsFormatExceptions (Cont.)13.4.1 Enclosing Code in a trytry Block A tryt
22、ry block encloses code that might throw exceptions and code that is skipped when an exception occurs. 2009 Pearson Education, Inc. All rights reserved.1913.4 Example: Handling DivideByZeroExceptionsDivideByZeroExceptions and FormatExceptionsFormatExceptions (Cont.) 13.4.2 Catching Exceptions When an
23、 exception occurs in a try block, a corresponding catchcatch block catches the exception and handles it. At least one catch block must immediately follow a try block. A catch block specifies an exception parameter representing the exception that the catch block can handle. Optionally, you can includ
24、e a catch block that does not specify an exception type to catch all exception types. 2009 Pearson Education, Inc. All rights reserved.2013.4 Example: Handling DivideByZeroExceptionsDivideByZeroExceptions and FormatExceptionsFormatExceptions (Cont.) 13.4.3 Uncaught Exceptions An uncaught exception (
25、or unhandled exception) is an exception for which there is no matching catchcatch block. If you run the application from Visual Studio with debugging, a window called the Exception Assistant (Fig. 13.3) appears. 2009 Pearson Education, Inc. All rights reserved.2113.4 Example: Handling DivideByZeroEx
26、ceptionsDivideByZeroExceptions and FormatExceptionsFormatExceptions (Cont.) Throw pointException AssistantFig. 13.3 | Exception Assistant. 2009 Pearson Education, Inc. All rights reserved.2213.4 Example: Handling DivideByZeroExceptionsDivideByZeroExceptions and FormatExceptionsFormatExceptions (Cont
27、.) 13.4.4 Termination Model of Exception Handling When a method called in a program or the CLR detects a problem, the method or the CLR throws an exception. The point at which an exception occurs is called the throw point If an exception occurs in a try block, program control immediately transfers t
28、o the first catch block matching the type of the thrown exception. After the exception is handled, program control resumes after the last catch block. This is known as the termination model of exception handling. 2009 Pearson Education, Inc. All rights reserved.2313.4 Example: Handling DivideByZeroE
29、xceptionsDivideByZeroExceptions and FormatExceptionsFormatExceptions (Cont.) Common Programming Error 13.1Logic errors can occur if you assume that after an exception is handled, control will return to the first statement after the throw point.Common Programming Error 13.2Specifying a comma-separate
30、d list of parameters in a catchcatch block is a syntax error. A catchcatch block can have at most one parameter. 2009 Pearson Education, Inc. All rights reserved.2413.5 .NET ExceptionException Hierarchy In C#, only objects of class ExceptionException and its derived classes may be thrown and caught.
31、 Exceptions thrown in other .NET languages can be caught with the general catch clause. 2009 Pearson Education, Inc. All rights reserved.2513.5 .NET ExceptionException Hierarchy (Cont.) 13.5.1 Class SystemExceptionSystemException Class ExceptionException is the base class of .NETs exception class hi
32、erarchy. The CLR generates SystemExceptionSystemExceptions, derived from class Exception, which can occur at any point during program execution. If a program attempts to access an out-of-range array index, the CLR throws an exception of type IndexOutOfRangeExceptionIndexOutOfRangeException. Attempti
33、ng to use a null reference causes a NullReferenceExceptionNullReferenceException. 2009 Pearson Education, Inc. All rights reserved.2613.5 .NET ExceptionException Hierarchy (Cont.) A catch block can use a base-class type to catch a hierarchy of related exceptions. A catch block that specifies a param
34、eter of type Exception can catch all exceptions. This technique makes sense only if the handling behavior is the same for a base class and all derived classes. Common Programming Error 13.3The compiler issues an error if a catchcatch block that catches a base-class exception is placed before a catch
35、catch block for any of that classs derived-class types. In this case, the base-class catchcatch block would catch all base-class and derived-class exceptions, so the derived-class exception handler would never executea possible logic error. 2009 Pearson Education, Inc. All rights reserved.2713.5 .NE
36、T ExceptionException Hierarchy (Cont.) 13.5.2 Determining Which Exceptions a Method Throws Search for “Convert.ToInt32 method” in the Index of the Visual Studio online documentation. Select the document entitled Convert.ToInt32 Method (System). In the document that describes the method, click the li
37、nk ToInt32(String). The Exceptions section indicates that method Convert.ToInt32 throws two exception types. 2009 Pearson Education, Inc. All rights reserved.2813.5 .NET ExceptionException Hierarchy (Cont.) Software Engineering Observation 13.1If a method throws exceptions, statements that invoke th
38、e method directly or indirectly should be placed in trytry blocks, and those exceptions should be caught and handled. 2009 Pearson Education, Inc. All rights reserved.2913.6 finallyfinally Block Programs frequently request and release resources dynamically. Operating systems typically prevent more t
39、han one program from manipulating a file. Therefore, the program should close the file(i.e., release the resource) so other programs can use it. If the file is not closed, a resource leak occurs. 2009 Pearson Education, Inc. All rights reserved.30Error-Prevention Tip 13.2The CLR does not completely
40、eliminate memory leaks. The CLR will not garbage collect an object until the program contains no more references to that object and even then there may be a delay until the memory is required. Thus, memory leaks can occur if programmers inadvertently keep references to unwanted objects. 13.6 finally
41、finally Block (Cont.) 2009 Pearson Education, Inc. All rights reserved.3113.6 finallyfinally Block (Cont.) Exceptions often occur while processing resources. Regardless of whether a program experiences exceptions, the program should close the file when it is no longer needed. C# provides the finally
42、 block, which is guaranteed to execute regardless of whether an exception occurs. This makes the finally block ideal to release resources from the corresponding try block. 2009 Pearson Education, Inc. All rights reserved.3213.6 finallyfinally Block (Cont.) Local variables in a try block cannot be ac
43、cessed in the corresponding finally block, so variables that must be accessed in both should be declared before the try block. Error-Prevention Tip 13.3A finallyfinally block typically contains code to release resources acquired in the corresponding trytry block, which makes the finallyfinally block
44、 an effective mechanism for eliminating resource leaks. 2009 Pearson Education, Inc. All rights reserved.3313.6 finallyfinally Block (Cont.)Performance Tip 13.1As a rule, resources should be released as soon as they are no longer needed in a program. This makes them available for reuse promptly.Comm
45、on Programming Error 13.4Placing the finallyfinally block before a catchcatch block is a syntax error. 2009 Pearson Education, Inc. All rights reserved.34OutlineUsingExceptions.cs UsingExceptions.cs ( 1 of 10 ) The application in Fig. 13.4 demonstrates that the finally block always executes. Main in
46、vokes method DoesNotThrowException. Main invokes method ThrowExceptionWithCatch. Fig. 13.4 | finally blocks always execute, even when no exception occurs. (Part 1 of 8.) 2009 Pearson Education, Inc. All rights reserved.35OutlineUsingExceptions.cs UsingExceptions.cs ( 2 of 10 ) Fig. 13.4 | finally bl
47、ocks always execute, even when no exception occurs. (Part 2 of 8.) 2009 Pearson Education, Inc. All rights reserved.36OutlineBecause the try block does not throw any exceptions, the catch block is ignored. UsingExceptions.cs UsingExceptions.cs ( 3 of 10 ) Fig. 13.4 | finally blocks always execute, e
48、ven when no exception occurs. (Part 3 of 8.) 2009 Pearson Education, Inc. All rights reserved.37OutlineThe finally block always executes. The try block throws an exception. The catch and finally blocks execute when the exception occurs. UsingExceptions.cs UsingExceptions.cs ( 4 of 10 ) Fig. 13.4 | f
49、inally blocks always execute, even when no exception occurs. (Part 4 of 8.) 2009 Pearson Education, Inc. All rights reserved.38OutlineThe catch and finally blocks execute when the exception occurs. The try block throws an exception. UsingExceptions.cs UsingExceptions.cs ( 5 of 10 ) Fig. 13.4 | final
50、ly blocks always execute, even when no exception occurs. (Part 5 of 8.) 2009 Pearson Education, Inc. All rights reserved.39OutlineThe finally block executes but the exception remains uncaught until after control returns to Main. The try block throws an exception. UsingExceptions.cs UsingExceptions.c
51、s ( 6 of 10 ) Fig. 13.4 | finally blocks always execute, even when no exception occurs. (Part 6 of 8.) 2009 Pearson Education, Inc. All rights reserved.40OutlineThe catch block rethrows the exception, which is then caught after control returns to Main. The catch and finally blocks execute when the e
52、xception occurs. UsingExceptions.cs UsingExceptions.cs ( 7 of 10 ) Fig. 13.4 | finally blocks always execute, even when no exception occurs. (Part 7 of 8.) 2009 Pearson Education, Inc. All rights reserved.41Fig. 13.4 | finally blocks always execute, even when no exception occurs. (Part 8 of 8.) 2009
53、 Pearson Education, Inc. All rights reserved.42Common Programming Error 13.5It is a compilation error if the argument of athrowthrowan exception objectis not of classExceptionException or one of its derived classes.Common Programming Error 13.6Throwing an exception from a finallyfinally block can be
54、 dangerous. If an uncaught exception is awaiting processing when the finallyfinally block executes, and the finallyfinally block throws a new exception that is not caught in the finallyfinally block, the first exception is lost, and the new exception is passed to the next enclosing trytry block. 200
55、9 Pearson Education, Inc. All rights reserved.43Error-Prevention Tip 13.4When placing code that can throw an exception in a finallyfinally block, always enclose the code in a trytry statement that catches the appropriate exception types. This prevents the loss of any uncaught and rethrown exceptions
56、 that occur before the finallyfinally block executes.Software Engineering Observation 13.2Do not place trytry blocks around every statement that might throw an exceptionthis can make programs difficult to read. Its better to place one trytry block around a significant portion of code, and follow thi
57、s trytry block with catchcatch blocks that handle each possible exception. Then follow the catchcatch blocks with a single finallyfinally block. Separate trytry blocks should be used when it is important to distinguish between multiple statements that can throw the same exception type. 2009 Pearson
58、Education, Inc. All rights reserved.4413.6 finallyfinally Block (Cont.) The usingusing statement simplifies writing code in which you obtain a resource. The general form of a using statement is:using ( ExampleObject e = new ExampleObject() ) e.SomeMethod(); 2009 Pearson Education, Inc. All rights re
59、served.4513.6 finallyfinally Block (Cont.) The using statement code is equivalent to ExampleObject e = new ExampleObject(); try e.SomeMethod(); finally if ( e != null ) ( ( IDisposable ) e ).Dispose(); 2009 Pearson Education, Inc. All rights reserved.4613.7 ExceptionException Properties Class Except
60、ions properties are used to formulate error messages indicating a caught exception. Property Message stores the error message associated with an Exception object. Property StackTrace contains a string that represents the method-call stack. 2009 Pearson Education, Inc. All rights reserved.4713.7 Exce
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 八年級(jí)地理下冊(cè)《7.1 面向海洋的開放地區(qū)-珠江三角洲》聽課評(píng)課記錄 新人教版
- 【人教版】河南省八年級(jí)地理上冊(cè)2.1地形和地勢(shì)聽課評(píng)課記錄2新版新人教版
- 北師大版歷史七年級(jí)下冊(cè)第12課《元朝的統(tǒng)一與拓展》聽課評(píng)課記錄
- 環(huán)境設(shè)計(jì)服務(wù)協(xié)議書(2篇)
- 七年級(jí)道德與法治上冊(cè)第一單元 成長(zhǎng)的節(jié)拍第一課中學(xué)時(shí)代第1框中學(xué)序曲聽課評(píng)課記錄(新人教版)
- 湘師大版道德與法治七年級(jí)上冊(cè)2.1《學(xué)習(xí)與成長(zhǎng)》聽課評(píng)課記錄
- 冀教版數(shù)學(xué)九年級(jí)下冊(cè)《回顧與反思》聽評(píng)課記錄10
- 人教版地理八年級(jí)下冊(cè)6.2《白山黑水-東北三省》聽課評(píng)課記錄2
- 蘇人版道德與法治九年級(jí)上冊(cè)6.1《共享發(fā)展成果》聽課評(píng)課記錄
- 部審湘教版七年級(jí)數(shù)學(xué)下冊(cè)6.1.1 第1課時(shí)《平均數(shù)》聽評(píng)課記錄
- 2025年買賣個(gè)人房屋合同(4篇)
- 2025代運(yùn)營(yíng)合同范本
- 武漢2025年湖北武漢理工大學(xué)管理人員招聘筆試歷年參考題庫(kù)附帶答案詳解
- 使用錯(cuò)誤評(píng)估報(bào)告(可用性工程)模版
- 2024年高考全國(guó)甲卷英語(yǔ)試卷(含答案)
- 2024年湖南高速鐵路職業(yè)技術(shù)學(xué)院?jiǎn)握新殬I(yè)技能測(cè)試題庫(kù)附答案
- 2024年4月浙江省00015英語(yǔ)二試題及答案含評(píng)分參考
- 臭和味檢測(cè)原始記錄表
- 小學(xué)英語(yǔ)26個(gè)字母標(biāo)準(zhǔn)手寫體卡片打印版
- 社區(qū)精神康復(fù)課件
評(píng)論
0/150
提交評(píng)論