Đang cố gắng Mã và bắt ngoại lệ C # làm cho nó dễ dàng để tách mã mà thực hiện các dòng chảy chính của chương trình từ xử lý lỗi code, bằng cách sử dụng các ngoại lệ và xử lý ngoại lệ. Để viết chương trình exceptionaware, bạn cần phải làm hai việc
Nội dung trích xuất từ tài liệu:
Trying Code and Catching Exceptions Trying Code and Catching ExceptionsC# makes it easy to separate the code that implements the main flow of the program fromthe error handling code, by using exceptions and exception handlers. To write exception-aware programs, you need to do two things: 1. Write your code inside a try block (try is a keyword). When the code runs, it attempts to execute all the statements inside the try block, and if none of the statements generates an exception, they all run, one after the other, to completion. However, if an error condition occurs, execution jumps out of the try block and into a catch handler. 2. Write one or more catch handlers (catch is a keyword) immediately after the try block to handle any possible error conditions. If any one of the statements inside the try block causes an error, the runtime generates and throws an exception. The runtime then examines the catch handlers after the try block and transfers control directly to a matching handler. Catch handlers are designed to trap particular exceptions, allowing you to provide different handlers for the different errors that can happen.Heres an example that uses a try block to attempt to convert some text fields into integervalues, call a method to calculate a value, and write the result to a text field. Converting astring to an integer requires that the string contains a valid representation and not somearbitrary sequence of characters. If the string contains invalid characters, the Int32.Parsemethod throws a FormatException, and execution transfers to the corresponding catchhandler. When the catch handler finishes, the program continues with the first statementafter the handler:try{ int leftHandSide = Int32.Parse(leftHandSideOperand.Text); int rightHandSide = Int32.Parse(rightHandSideOperand.Text); int answer = doCalculation(leftHandSide, rightHandSide); result.Text = answer.ToString();}catch (FormatException fEx){ // Handle the exception ...}Handling an ExceptionThe catch handler uses syntax similar to that used by a method parameter to specify theexception to be caught. In the previous example, when a FormatException is thrown, thefEx variable is populated with an object containing the details of the exception. TheFormatException type has a number of fields that you can examine to determine the exactcause of the exception. Many of these fields are common to all exceptions. For example,the Message field contains a text description of the error that caused the exception. Youcan use this information when handling the exception, recording the details to a log file,or outputting a meaningful message to the user and asking them to try again, for example.Unhandled ExceptionsWhat happens if a try block throws an exception and there is no corresponding catchhandler? In the previous example, it is possible that the leftHandSideOperand fieldcontains the string representation of a valid integer, but the integer that it represents isoutside of the range of valid integers supported by C# (for example, “2147483648”). Inthis case, the Int32.Parse statement will throw an OverflowException, which will not becaught by the catch handler as it specifies that it catches FormatException. If the tryblock is part of a method, the method finishes and returns to the calling method. If thecalling method uses a try block, the common language runtime attempts to locate amatching catch handler after the try block and execute it. If the calling method does notuse a try block, or there is no matching catch handler, the calling method terminates andreturns to its caller where the process is repeated. If a matching catch handler iseventually found, it runs and execution continues with the first statement after the catchhandler in the catching method.IMPORTANTNotice that after catching an exception, execution continues in the method containing thecatch block that caught the exception. Control does not return to the method that causedthe exception.If, after cascading back through the list of calling methods, the common languageruntime is unable to find a matching catch handler, the program terminates with anunhandled exception. If you are running the application in Visual Studio 2005 in Debugmode (you selected Start Debugging in the Debug menu to run the application), thefollowing information dialog box appears and the application drops into the debugger,allowing you to determine the cause of the exception:Using Multiple catch HandlersThe previous discussion highlighted how different errors throw different kinds ofexceptions to represent different kinds of failure. To cope with these situations, you cansupply multiple catch handlers, one after the other, like this:try{ int leftHandSide = Int32.Parse(leftHandSideOperand.Text); int rightHandSide = Int32.Parse(rightHandSideOperand.Text); int answer = doCalculation(leftHandSide, rightHandSide); result.Text = answer.ToString();}catch (FormatException fEx){ //...}catch (OverflowException oEx){ //...}Catching Multiple ExceptionsThe exception-catching mechanism of the common language runtime is prettycomprehensive. There are many different exceptions defined in the .NET Framework,and any programs you write will be able to throw most of them! It is highly unlikely thatyou will want to write catch handlers for every possible exception that your code canthrow. So how do you ensure that all possible exceptions are caught and handled?The answer to this question lies in the way the different exceptions are related to eachother. Exceptions are organized into families called inheritance hierarchies (you willlearn about inheritance in Chapter 12, “Working with Inheritance”). FormatExceptionand OverflowException both belong to a family called SystemException, as do a number ...