Catch块内代码的限制
本文关键字:代码 Catch | 更新日期: 2023-09-27 17:50:50
我们可以在c#的try Catch的Catch块中编写任何代码语句吗?或者有什么限制我们不能或不应该在c#的Catch块中写什么?
不能在catch块中使用yield
或await
。所以下面两个代码不能编译:
public IEnumerable<int> SomeSequence()
{
try
{
//do something
}
catch
{
yield 1; //error
}
}
或
public async int SomeFuncAsync()
{
try
{
//do something
}
catch
{
await Task.Delay(1000); //error
}
}
你可以很容易地解决这个问题:
public async int SomeFuncAsync()
{
Exception ex = null;
try
{
//do something
}
catch(Exception exc)
{
ex = exc;
}
if(ex != null) await Task.Delay(1000); // no error
}