Nó có thể gọi bất kỳ phương pháp trong bối cảnh của một biểu thức query. Tuy nhiên, chúng tôi khuyên bạn nên tránh gọi bất kỳ method trong một biểu thức query có thể tạo ra một tác dụng phụ chẳng hạn như thay đổi nội dung của nguồn dữ liệu hoặc throw một ngoại lệ. Ví dụ này cho thấy làm thế nào để tránh trường hợp ngoại lệ nâng cao khi bạn gọi phương thức trong một biểu thức query mà không vi phạm nói chung. NET Framework hướng dẫn về xử lý ngoại lệ. Những trạng thái hướng dẫn đó thì có thể bắt một ngoại lệ cụ thể khi bạn hiểu tại sao nó sẽ được ném ra trong một bối cảnh cụ thể.
Ví dụ sau đây cho thấy làm thế nào để di chuyển mã xử lý ngoại lệ bên ngoài một biểu thức query. Điều này chỉ có thể khi các method không phụ thuộc vào bất kỳ các biến local để truy vấn.
class ExceptionsOutsideQuery
{
static void Main()
{
// DO THIS with a datasource that might
// throw an exception. It is easier to deal with
// outside of the query expression.
IEnumerable
try
{
dataSource = GetData();
}
catch (InvalidOperationException)
{
// Handle (or don't handle) the exception
// in the way that is appropriate for your application.
Console.WriteLine("Invalid operation");
goto Exit;
}
// If we get here, it is safe to proceed.
var query = from i in dataSource
select i * i;
foreach (var i in query)
Console.WriteLine(i.ToString());
//Keep the console window open in debug mode
Exit:
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
// A data source that is very likely to throw an exception!
static IEnumerable
{
throw new InvalidOperationException();
}
}
Trong một số trường hợp, câu trả lời tốt nhất để một ngoại lệ được thrown từ bên trong một query có thể để ngăn chặn việc thực hiện query ngay lập tức. Ví dụ sau đây cho thấy làm thế nào để xử lý các trường hợp ngoại lệ có thể được thrown từ bên trong một thân query. Giả sử rằng SomeMethodThatMightThrow khả năng có thể gây ra một ngoại lệ đòi hỏi phải thực hiện query để ngăn chặn.
Lưu ý rằng khối try bao bọc các vòng lặp foreach, và không phải là query chính nó. Điều này là do các vòng lặp foreach là điểm mà tại đó các truy vấn được thực thi.
class QueryThatThrows
{
static void Main()
{
// Data source.
string[] files = { "fileA.txt", "fileB.txt", "fileC.txt" };
// Demonstration query that throws.
var exceptionDemoQuery = from file in files
let n = SomeMethodThatMightThrow(file)
select n;
// Runtime exceptions are thrown when query is executed.
// Therefore they must be handled in the foreach loop.
try
{
foreach (var item in exceptionDemoQuery)
{
Console.WriteLine("Processing {0}", item);
}
}
// Catch whatever exception you expect to raise
// and/or do any necessary cleanup in a finally block
catch (InvalidOperationException e)
{
Console.WriteLine(e.Message);
}
//Keep the console window open in debug mode
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
// Not very useful as a general purpose method.
static string SomeMethodThatMightThrow(string s)
{
if (s[4] == 'C')
throw new InvalidOperationException();
return @"C:\newFolder\" + s;
}
}
/* Output:
Processing C:\newFolder\fileA.txt
Processing C:\newFolder\fileB.txt
Operation is not valid due to the current state of the object.
*/
DangTrung.
Không có nhận xét nào:
Đăng nhận xét