Đang chuẩn bị liên kết để tải về tài liệu:
Beginning C# 2005 Databases From Novice to Professional phần 8

Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ

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ệ ADO.NET. 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 ADO.NET 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 ADO.NET 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 cmd.CommandType CommandType.StoredProcedure Deliberately fail to specify the procedure cmd.CommandText 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 conn.Open Create data reader SqlDataReader dr cmd.ExecuteReader Close reader dr.Close To handle the exception yourself you code two catch clauses catch System.Data.SqlClient.SqlException ex string str str Source ex.Source str n Exception Message ex.Message MessageBox.Show str Database Exception catch System.Exception ex string str str Source ex.Source str n Exception Message ex.Message MessageBox.Show 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 .