...C10. Exception Handling.pdf

11 130 0
...C10. Exception Handling.pdf

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Chương 7XỬ LÝ NGOẠI LỆ (Exception Handling)Sau khi kết thúc chương này, bạn có thể nắm được các nội dung sau: Định nghĩa một ngoại lệ (exception) Hiểu được mục đích của việc xử lý ngoại lệ Hiểu được các kiểu ngoại lệ khác nhau trong Java Mô tả mô hình xử lý ngoại lệ Hiểu được các khối lệnh chứa nhiều catch Mô tả cách sử dụng các khối ‘try’, ‘catch’ và ‘finally’ Giải thích cách sử dụng các từ khoá ‘throw’ và ‘throws’ Tự tạo ra các ngoại lệ 7.1 Giới thiệuException là một lỗi đặc biệt. Lỗi này xuất hiện vào lúc thực thi chương trình. Các trạng thái không bình thường xảy ra trong khi thi hành chương trình tạo ra các exception. Những trạng thái này không được biết trước trong khi ta đang xây dựng chương trình. Nếu bạn không phân phối các trạng thái này thì exception có thể bị kết thúc đột ngột. Ví dụ, việc chia cho 0 sẽ tạo một lỗi trong chương trình. Ngôn ngữ Java cung cấp bộ máy dùng để xử lý ngoại lệ rất tuyệt vời. Việc xử lý này làm hạn chế tối đa trường hợp hệ thống bị phá vỡ (crash) hay hệ thống bị ngắt đột ngột. Tính năng này làm cho Java là một ngôn ngữ lập trình mạnh.7.2 Mục đích của việc xử lý ngoại lệMột chương trình nên có cơ chế xử lý ngoại lệ thích hợp. Nếu không, chương trình sẽ bị ngắt khi một exception xảy ra. Trong trường hợp đó, tất cả các nguồn tài nguyên mà hệ thống trước kia phân phối sẽ được di dời trong cùng trạng thái. Điều này gây lãng phí tài nguyên. Để tránh trường hợp này, tất cả các nguồn tài nguyên mà hệ thống phân phối nên được thu hồi lại. Tiến trình này đòi hỏi cơ chế xử lý ngoại lệ thích hợp.Cho ví dụ, xét thao tác nhập xuất (I/O) trong một tập tin. Nếu việc chuyển đổi kiểu dữ liệu không thực hiện đúng, một ngoại lệ sẽ xảy ra và chương trình bị hủy mà không đóng lại tập tin. Lúc đó tập tin dễ bị hư hại và các nguồn tài nguyên được cấp phát cho tập tin không được thu hồi lại cho hệ thống.7.3 Xử lý ngoại lệKhi một ngoại lệ xảy ra, đối tượng tương ứng với ngoại lệ đó được tạo ra. Đối tượng này sau đó được truyền cho phương thức là nơi mà ngoại lệ xảy ra. Đối tượng này chứa thông tin chi tiết về ngoại lệ. Thông tin này có thể được nhận về và được xử lý. Các môi trường runtime như ‘IllegalAccessException’, ‘EmptyStackException’ v.v… có thể chặn được các ngoại lệ. Đoạn mã trong chương trình đôi khi có thể tạo ra các ngoại lệ. Lớp ‘throwable’ được Java cung cấp là lớp trên nhất của lớp Exception , lớp này là lớp cha của các ngoại lệ Chương 7: Xử lý ngoại lệ (Exception Handling) 27 khác nhau.7.4 Mô hình xử lý ngoại lệTrong Java, mô hình xử lý ngoại lệ kiểm tra việc xử lý những hiệu ứng lề (lỗi), được biết đến là mô hình ‘catch và throw’. Trong mô hình này, khi một lỗi xảy ra, một ngoại lệ sẽ bị chặn và được đưa vào trong một khối. Người lập trình viên nên xét các trạng thái ngoại lệ độc lập nhau từ việc điều khiển thông thường trong chương trình. Các ngoại lệ phải được bắt giữ nếu không chương trình sẽ bị ngắt.Ngôn ngữ Java cung cấp 5 từ khoá sau để xử lý các ngoại lệ: try catch throw throws finallyDưới đây là cấu trúc của mô hình xử lý N gôn ngữ C # T rần V ăn T èo tvteo@agu.edu.vn 01/06/2006 N g ôn n g ữ C # T hụ lý B iệt lệ (E xception H andler) X lý nhữ ng sai lầm nhữ ng điều kiện b ất b ình th ng n C onsole.W riteL ine(“N hập vào m ột số”); int i = int.Parse( Console.ReadLine( ) ); n n n n n Error Đ ố i tư ợ ng exception S dụng try -catch N h iều khối catch C âu lệnh throw M ệnh đề finally 01/06/2006 N g ôn n g ữ C # Đ ố i tư ợ ng E x cep tio n Exception SystemException OutOfMemoryException IOException NullReferenceException ApplicationException 01/06/2006 N g ôn n g ữ C # S dụng khối lệnh try try catch n n Đ ặt code khối try T h ụ lý biệt lệ tro n g kh ố i catch try{ Console.WriteLine(“N hập vào m ột số”); int i = int.Parse( Console.ReadLine( ) ); } catch( OverflowException caught) { Console.WriteLine( caught.Message ); } 01/06/2006 N g ôn n g ữ C # Code Error handling N hiều khối catch n n M ỗ i khối catch bắt m ột lớ p biệt lệ lệ B iệt lệ dẫn xuất p h ải th ự c h iện trư c b iệt lệ sở try{ Console.WriteLine(“N hập vào m ột số”); int i = int.Parse( Console.ReadLine( ) ); } catch( OverflowException caught){ Console.WriteLine( caught ); } catch( DivideByZeroException caught ){ Console.WriteLine( caught ); } 01/06/2006 N g ôn n g ữ C # C âu lệnh throw n n B áo động m ột điều kiện bất bình thư n g kh i đ an g th i h àn h, tống m ộ t b iệt lệ G i m ột thông điệp biệt lệ có ý nghĩa throw [expression]; if( minute < || minute > 60 ) { throw new InvalidTimeException( minute + “ is not a valid m inute.” ); // !! Not reached !! } 01/06/2006 N g ôn n g ữ C # M ệnh đề finally n n C ác lệnh khối finally đư ợ c th ự c h iện D ù ng để “dọn d ẹp ” tài n g u yên n ch iếm d ụ n g b ộ nhớ khối try try{ Console.WriteLine(“Đ ọc tập tin đây.”); } catch( IOException e){ Console.WriteLine(“L ổi m tập tin.”); } finally{ Console.WriteLine(“Đ óng tập tin đây.”); } 01/06/2006 N g ôn n g ữ C # L p S ystem E x cep tio n Properties n • • • • HelpLink K ết nối tập tin help gắn liền vớ i biệt lệ InnerException Đ ối tư ợ ng E xception hành Message T hông điệp m ô tả biệt lệ hành Source T ên ứ ng dụng đối tư ợ ng gây biệt lệ Methods n • • Equals ToString S o sánh hai thể O verridden C huổi biệt lệ hành catch( IOException e){ Console.WriteLine ( e.Message ); Console.WriteLine ( e ); } 01/06/2006 N g ôn n g ữ C # T ạo m ột biệt lệ n P hải đư ợ c dẫn xuất từ S ystem A plicationE xception public class SVException : System.ApplicationException{ public SVException( string msg) : base ( msg ){ } } //End SVException public void InsertSV( ){ if( _SoLuong == _MaxSV ){ SVException e = new SVException(“L p n ày đ ã đ ủ sinh v iên!”); throw e ; } } //End InsertSV try{ sv.InsertSV( ); } catch( SVException e){ Console.WriteLine( e.Message ); 01/06/2006 N g ôn n g ữ C # } T ung lại biệt lệ K hối catch sau sử a sai lại tung biệt lệ cho khối try nằm public void FuncA( ){ throw new DivideByZeroException(“ L ổ i chia cho zero ”); } public void FuncB( ){ try{ FuncA( ) }catch( ArithmeticException e ){ throw; } } public void FuncC( ){ try{ FuncB( ) }catch(DivideByZeroException e ){ Console.WriteLine( e.Message ); } 01/06/2006 N g ôn n g ữ C # } 10 Q&A 01/06/2006 N g ôn n g ữ C # 11 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-WesleyChapter 16Exception Handling Slide 16- 3Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-WesleyOverview16.1 Exception-Handling Basics 16.2 Programming Techniques for Exception Handling Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley16.1Exception-Handling Basics Slide 16- 5Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-WesleyException Handling BasicsIt is often easier to write a program by firstassuming that nothing incorrect will happenOnce it works correctly for the expected cases, add code to handle the exceptional casesException handling is commonly used to handleerror situationsOnce an error is handled, it is no longer an error Slide 16- 6Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-WesleyFunctions and Exception HandlingA common use of exception handling:Functions with a special case that is handled in different ways depending on how the function is usedIf the function is used in different programs, each program may require a different action when the special case occurs Slide 16- 7Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-WesleyException Handling MechanismIn C++, exception handling proceeds by:Some library software or your code signals that something unusual has happenedThis is called throwing an exceptionAt some other place in your program you place the code that deals with the exceptional caseThis is called handling the exception Slide 16- 8Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-WesleyA Toy ExampleException handling is meant to be used sparinglyin situations that are generally not reasonableintroductory examplesFor this example:Suppose milk is so important that we almost never run outWe still would like our program to handle the situation of running out of milk Slide 16- 9Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-WesleyThe Milk Example (cont.)Code to handle the normal situations involvingmilk, might be: cout << "Enter number of donuts:\n"; cin >> donuts; cout << "Enter number of glasses of milk:\n"; cin >> milk; dpg = donuts /static_cast<double>(milk); cout << donuts << " donuts.\n" << milk << " glasses of milk.\n" << "You have " << dpg << " donuts per glass of milk.\n"; Slide 16- 10Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-WesleyIf there is no milk, the code on the previous slideresults in a division by zeroWe could add a test case for this situation shows the program with the test case shows the program rewritten using an exceptionDisplay 16.1Display 16.2 (1-2)The No Milk Problem [...]... conversions are done with exceptions  if double is in the exception specification, an int cannot be thrown unless int is also in the exception specification Slide 16- 35 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Programming Techniques for Exception Handling  A guideline for exception handling is to separate throwing an exception and catching an exception into separate... Pearson Addison-Wesley Exceptions Not Listed  If an exception is not listed in an exception specification and not caught by the function:  The program ends  If there is no exception specification at h t t p : / / r e s o u r c e . r e n e s a s . c o m Page 84 Chapter 7 Exception Handling Exception handling is classified into reset and interrupts and the interrupt function is indispensable for control using programs. It is almost always used when a timer is used and is also required for effective data input/output. To write the program you have made to the ROM for execution, you also need to understand how reset works. The concepts of reset and interrupts, however, are difficult to understand for beginners. Since practical uses are not mentioned in this chapter, you may not get a clear idea of them. The effects of interrupts are described in chapters relating to timers and serial interface. Here, you should fully understand the following key items: interrupt mask bit in the CCR, vector addresses and storage of the PC and CCR values. Note: Some IC signal names have bars over them to indicate negative logic. In the contents of the CD-ROM, however, no bar can be placed on them since they are written in HTML format. Still, bars are added to negative logic signals in figures included as images. The following are negative logic signals: 7.1 What Is Exception Handling? The CPU sometimes shows special operation called "exception handling". Exception handling refers to the operation that moves execution not to the next instruction but to another program after the current instruction is completely executed if any exception handling source is generated while the CPU is executing the main routine. The program to which execution is moved by exception handling is referred to as an "exception handling routine". h t t p : / / r e s o u r c e . r e n e s a s . c o m Page 85 Figure 7.1: Exception Handling Operation Overview The H8/3048 has 42 types of exception handling sources, which are classified into one reset and 41 interrupts. Reset is mainly designed to start execution from a particular program after turning the microcomputer on. Interrupts are designed to move operation to an exception handling routine when an interrupt source is generated during program execution and return operation to the original program after the exception handling routine has been executed completely. Figure 7.2: Types of Exception Handling Sources Although what generates an exception handling source depends on the type, all types of exception handling routines employ the vector method. This method is designed to notify the CPU of the start address of an exception handling routine. The details are described in the following sections. 7.2 Reset 7.2.1 Reset Sources and Operation Reset is generated for two purposes. One is to start execution from a particular program after turning the microcomputer on. This program is called the "main routine". The other is to stop any program being executed by the CPU and resume processing from the same state when the power is turned on again. Figure 7.3 shows reset sources: h t t p : / / r e s o u r c e . r e n e s a s . c o m Page 86 Figure 7.3: Reset Sources The CPU shows the operation described in Figure 7.4 after reset is generated. Figure 7.4: Reset Operation h t t p : / / r e s o u r c e . r e n e s a s . c o m Page 87 After reset is generated, the CPU stops any program being executed, loads the reset vector to the PC and fetches an instruction from this address to execute it. In other words, reset generation always causes the main routine stored in the address indicated by the reset vector to be executed. After reset is generated to start main routine execution, processing cannot be returned to the original program to continue. Reset generation means that the microcomputer starts processing from the initial state. When the microcomputer starts operation, users are required to set the program to Chương 7 XỬ LÝ NGOẠI LỆ (Exception Handling) Sau khi kết thúc chương này, bạn có thể nắm được các nội dung sau:  Định nghĩa một ngoại lệ (exception)  Hiểu được mục đích của việc xử lý ngoại lệ  Hiểu được các kiểu ngoại lệ khác nhau trong Java  Mô tả mô hình xử lý ngoại lệ  Hiểu được các khối lệnh chứa nhiều catch  Mô tả cách sử dụng các khối ‘try’, ‘catch’ và ‘finally’  Giải thích cách sử dụng các từ khoá ‘throw’ và ‘throws’  Tự tạo ra các ngoại lệ 7.1 Giới thiệu Exception là một lỗi đặc biệt. Lỗi này xuất hiện vào lúc thực thi chương trình. Các trạng thái không bình thường xảy ra trong khi thi hành chương trình tạo ra các exception. Những trạng thái này không được biết trước trong khi ta đang xây dựng chương trình. Nếu bạn không phân phối các trạng thái này thì exception có thể bị kết thúc đột ngột. Ví dụ, việc chia cho 0 sẽ tạo một lỗi trong chương trình. Ngôn ngữ Java cung cấp bộ máy dùng để xử lý ngoại lệ rất tuyệt vời. Việc xử lý này làm hạn chế tối đa trường hợp hệ thống bị phá vỡ (crash) hay hệ thống bị ngắt đột ngột. Tính năng này làm cho Java là một ngôn ngữ lập trình mạnh. 7.2 Mục đích của việc xử lý ngoại lệ Một chương trình nên có cơ chế xử lý ngoại lệ thích hợp. Nếu không, chương trình sẽ bị ngắt khi một exception xảy ra. Trong trường hợp đó, tất cả các nguồn tài nguyên mà hệ thống trước kia phân phối sẽ được di dời trong cùng trạng thái. Điều này gây lãng phí tài nguyên. Để tránh trường hợp này, tất cả các nguồn tài nguyên mà hệ thống phân phối nên được thu hồi lại. Tiến trình này đòi hỏi cơ chế xử lý ngoại lệ thích hợp. Cho ví dụ, xét thao tác nhập xuất (I/O) trong một tập tin. Nếu việc chuyển đổi kiểu dữ liệu không thực hiện đúng, một ngoại lệ sẽ xảy ra và chương trình bị hủy mà không đóng lại tập tin. Lúc đó tập tin dễ bị hư hại và các nguồn tài nguyên được cấp phát cho tập tin không được thu hồi lại cho hệ thống. 7.3 Xử lý ngoại lệ Chương 7: Xử lý ngoại lệ (Exception Handling) 27 Khi một ngoại lệ xảy ra, đối tượng tương ứng với ngoại lệ đó được tạo ra. Đối tượng này sau đó được truyền cho phương thức là nơi mà ngoại lệ xảy ra. Đối tượng này chứa thông tin chi tiết về ngoại lệ. Thông tin này có thể được nhận về và được xử lý. Các môi trường runtime như ‘IllegalAccessException’, ‘EmptyStackException’ v.v… có thể chặn được các ngoại lệ. Đoạn mã trong chương trình đôi khi có thể tạo ra các ngoại lệ. Lớp ‘throwable’ được Java cung cấp là lớp trên nhất của lớp Exception , lớp này là lớp cha của các ngoại lệ khác nhau. 7.4 Mô hình xử lý ngoại lệ Trong Java, mô hình xử lý ngoại lệ kiểm tra việc xử lý những hiệu ứng lề (lỗi), được biết đến là mô hình ‘catch và throw’. Trong mô hình này, khi một lỗi xảy ra, một ngoại lệ sẽ bị chặn và được đưa vào trong một khối. Người lập trình viên nên xét các trạng thái ngoại lệ độc lập nhau từ việc điều khiển thông thường trong chương trình. Các ngoại lệ phải được bắt giữ nếu không chương trình sẽ bị ngắt. Ngôn ngữ Java cung cấp 5 từ khoá sau để xử lý các ngoại lệ:  try  catch  throw  throws  finally Dưới đây là cấu trúc của mô hình xử lý ngoại lệ: try { // place code that is expected to throw an exception } catch(Exception e1) { // If an exception is thrown in ‘try’, which is of type e1, then perform // necessary actions here, else go to the next catch block } catch(Exception e2) { // If Chapter 4. Exception Handling Hoàng Hữu Việt IT Faculty, Vinh University A reference of MSDN Library for Visual Studio 2005 Slide 2 Chapter 4. Exception Handling Contents  Introduction  Exception Class  Try statement  Example Slide 3 Chapter 4. Exception Handling Introduction  An exception is any error condition or unexpected behavior encountered by an executing program.  Exceptions can be raised because of a fault in your code or in code you call (such as a shared library), unavailable operating system resources, unexpected conditions the common language runtime encounters (such as code that cannot be verified), and so on. Slide 4 Chapter 4. Exception Handling Introduction  In the .NET Framework, an exception is an object that inherits from the Exception Class class. An exception is thrown from an area of code where a problem has occurred. The exception is passed up the stack until the application handles it or the program terminates. Slide 5 Chapter 4. Exception Handling Exception Class  The Exception class is the base class from which exceptions inherit. Most exception objects are instances of some derived class of Exception, but you can throw any object that derives from the Object class as an exception. Slide 6 Chapter 4. Exception Handling Exception Class  Common Properties  Message: Provides details about the cause of an exception.  StackTrace: Contains a stack trace that can be used to determine where an error occurred. The stack trace includes the source file name and program line number if debugging information is available. Slide 7 Chapter 4. Exception Handling Try statement  A common usage of catch and finally together is to obtain and use resources in a try block, deal with exceptional circumstances in a catch block, and release the resources in the finally block Slide 8 Chapter 4. Exception Handling try statement  try catch finally Statement try { 1. Include codes in which exceptions might occur. } catch (Exception ) { 2. Represent types of exceptions the catch can handle. } finally { 3.(Optional) codes present here will always execute. } Slide 9 Chapter 4. Exception Handling Example  Example: Divide by zero Error Message Error Message Slide 10 Chapter 4. Exception Handling Example  Code pattern private void btnDivide_Click(object sender, EventArgs e) { textBox3.Clear(); try { int a = Convert.ToInt32(textBox1.Text); int b = Convert.ToInt32(textBox2.Text); int c = a / b; textBox3.Text = c.ToString(); } catch(Exception ex) { MessageBox.Show(ex.Message); } } ... class SVException : System.ApplicationException{ public SVException( string msg) : base ( msg ){ } } //End SVException public void InsertSV( ){ if( _SoLuong == _MaxSV ){ SVException e = new SVException(“L... ng exception S dụng try -catch N h iều khối catch C âu lệnh throw M ệnh đề finally 01/06/2006 N g ôn n g ữ C # Đ ố i tư ợ ng E x cep tio n Exception SystemException OutOfMemoryException IOException... DivideByZeroException(“ L ổ i chia cho zero ”); } public void FuncB( ){ try{ FuncA( ) }catch( ArithmeticException e ){ throw; } } public void FuncC( ){ try{ FuncB( ) }catch(DivideByZeroException

Ngày đăng: 05/11/2017, 03:41

Tài liệu cùng người dùng

Tài liệu liên quan