TAILIEUCHUNG - Throwing Exceptions

Ném ngoại lệ Giả sử bạn đang thực hiện một phương pháp monthName gọi là chấp nhận một đối số int đơn và trả về tên của các tháng tương ứng. Ví dụ, monthName (1) trả về "tháng Giêng." | 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 .

TAILIEUCHUNG - Chia sẻ tài liệu không giới hạn
Địa chỉ : 444 Hoang Hoa Tham, Hanoi, Viet Nam
Website : tailieuchung.com
Email : tailieuchung20@gmail.com
Tailieuchung.com là thư viện tài liệu trực tuyến, nơi chia sẽ trao đổi hàng triệu tài liệu như luận văn đồ án, sách, giáo trình, đề thi.
Chúng tôi không chịu trách nhiệm liên quan đến các vấn đề bản quyền nội dung tài liệu được thành viên tự nguyện đăng tải lên, nếu phát hiện thấy tài liệu xấu hoặc tài liệu có bản quyền xin hãy email cho chúng tôi.
Đã 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.