tailieunhanh - Beginning C# 2005 Databases From Novice to Professional phần 8

Nó sẽ được đánh giá cao bất thường để bỏ lỡ thiết lập thuộc tính CommandText. Tuy nhiên, đây là một cách thiết thực để gây ra một ngoại lệ . Bạn chỉ rõ các lệnh cho một cuộc gọi thủ tục lưu trữ, nhưng bạn không chỉ định các thủ tục lưu trữ để gọi | CHAPTER 13 HANDLING EXCEPTIONS 339 10. Run the program with Ctrl F5. Click the Exception-1 button and you ll see the message box shown in Figure 13-3. Click OK. Figure 13-3. Handled exception message 11. When the message box in Figure 13-4 appears click OK then close the window. Figure 13-4. Message from finally block How It Works It would be highly unusual to miss setting the CommandText property. However this is an expedient way to cause an exception. You specify the command for a stored procedure call but you don t specify the stored procedure to call Specify that a stored procedure is to be executed Deliberately fail to specify the procedure sp_Select_AllEmployees so when you call the ExecuteReader method you get an exception as shown in Figure 13-2. Though it s an unhandled exception it still gives you an accurate diagnostic ExecuteReader CommandText property has not been intiailized. and it even gives you the option to continue or quit. However leaving this decision to users isn t a very good idea. After seeing what happens without handling the exception you place the call in a try block 340 CHAPTER 13 HANDLING EXCEPTIONS try Open connection Create data reader SqlDataReader dr Close reader To handle the exception yourself you code two catch clauses catch ex string str str Source str n Exception Message str Database Exception catch ex string str str Source str n Exception Message str Non-Database Exception In the first catch clause you specify a database exception type. The second catch clause which produces the message box in Figure 13-3 is a generic block that catches all types of exceptions. Note the caption of the message box in this catch block. It says Non-Database Exception. Although you may think that a failure to .