tailieunhanh - Most Classes Describes

Throwing Exceptions Suppose you are implementing a method called monthName that accepts a single int argument and returns the name of the corresponding month. For example, monthName(1) returns “January.” | Throwing Exceptions Suppose you are implementing a method called monthName that accepts a single int argument and returns the name of the corresponding month. For example monthName l returns January. The question is what should the method return when the integer argument is less than 1 or greater than 12 The best answer is that the method shouldn t return anything at all it should throw an exception. The .NET Framework class libraries contain lots of exception classes specifically designed for situations such as this. Most of the time you will find that one of these classes describes your exceptional condition. If not you can easily create your own exception class but you need to know a bit more about the C language before you can do that. In this case the existing .NET Framework ArgumentOutOfRangeException class is just right public static string monthName int month switch month case 1 return January case 2 return February . case 12 return December default throw new ArgumentOutOfRangeException Bad month Notice how the default case uses a throw statement to generate an exception. The throw statement needs an exception to throw. This example uses an expression that creates a new ArgumentOutOfRangeException object. The object is initialized with a string that will populate its Message property by using a constructor. Constructors are covered in detail in Chapter 7 Creating and Managing Classes and Objects. In the following exercises you will add code that throws and catches exceptions to the MathsOperators project. Throw your own exception 1. Return to Visual Studio 2005 and make sure the MathsOperators solution is still open. 2. On the Debug menu click Start Without Debugging. 3. Type 24 in the left operand text box type 36 in the right operand text box and then click Calculate. The value 0 ppears in the Result text box. The fact that you have not selected an operator option is not immediately obvious. It would be useful to write a diagnostic message in the Result .

TÀI LIỆU LIÊN QUAN
10    127    1
6    150    1
7    127    1
5    125    1
6    127    1
6    115    1
6    122    1
6    174    1
7    122    1
crossorigin="anonymous">
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.