C# 在C中发生异常后如何继续
输出为 正在处理C:\newFolder\fileA.txt 由于对象的当前状态,操作无效 但我需要输出为: 正在处理C:\newFolder\fileA.txt 由于对象的当前状态,操作无效 由于对象的当前状态,操作无效 正在处理C:\newFolder\field.txtC# 在C中发生异常后如何继续,c#,asp.net,C#,Asp.net,输出为 正在处理C:\newFolder\fileA.txt 由于对象的当前状态,操作无效 但我需要输出为: 正在处理C:\newFolder\fileA.txt 由于对象的当前状态,操作无效 由于对象的当前状态,操作无效 正在处理C:\newFolder\field.txt 请在此方面提供帮助………静态字符串somemethods可能会通过字符串s { 尝试 { 如果s[4]=“C” 抛出新的InvalidOperationException; 返回@C:\newFolder\+s; } 捕获
请在此方面提供帮助………静态字符串somemethods可能会通过字符串s { 尝试 { 如果s[4]=“C” 抛出新的InvalidOperationException; 返回@C:\newFolder\+s; } 捕获无效操作异常 { 返回e.消息; } 特例 { 返回其他错误; }
static string SomeMethodThatMightThrow(string s)
{
if (s[4] == 'C')
throw new InvalidOperationException();
return @"C:\newFolder\" + s;
}
static void Main(string[] args)
{
string[] files = { "fileA.txt", "B.txC", "fileC.txt","fileD.txt" };
var exceptionDemoQuery =
from file in files
let n = SomeMethodThatMightThrow(file)
select n;
try
{
foreach (var item in exceptionDemoQuery)
{
Console.WriteLine("Processing {0}", item);
}
}
catch (InvalidOperationException e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
}执行一些方法,这些方法可能会在foreach中包含try/catch
例如:
}
static void Main(string[] args)
{
string[] files = { "fileA.txt", "B.txC", "fileC.txt","fileD.txt" };
var exceptionDemoQuery =
from file in files
let n = SomeMethodThatMightThrow(file)
select n;
foreach (var item in exceptionDemoQuery)
{
Console.WriteLine("Processing {0}", item);
}
Console.WriteLine("Press any key to exit");
Console.ReadKey();
我猜您的操作结果应该包含实际结果和异常,以防发生-例如
var exceptionDemoQuery =
from file in files
select file;
foreach (var item in exceptionDemoQuery)
{
try
{
Console.WriteLine("Processing {0}", item);
var n = SomeMethodThatMightThrow(item);
}
catch (Exception ex)
{
Console.WriteLine(e.Message);
}
}
我已经使用OperationWrapper,假设您可能有许多这样的函数,否则您可能会更改实际函数本身。我想这是明天的作业?我对投票结果感到惊讶。我猜这显然是一个极其草率、毫不费劲的问题。确实是正确的解决方案,但可能不适合OP的程序结构-@VinayC:不是这样,我将展开。我的评论基于这样一个假设,OP将在某个不同的位置为每个循环提供可枚举的结构,并将其作为输入,其中一些可能抛出的方法可能实际具有不同的可插入实现。但实际上,我可能想象得太多了——你们看到的解决方案可能对OP有效。
static Func<string, Tuple<string, Exception>> OperationWrapper(Func<string, string> op)
{
return s => {
try
{
return Tuple.Create<string, Exception>(op(s), null);
}
catch(Exception ex)
{
return Tuple.Create<string, Exception>(null, ex);
}
};
}
// goes rest of the code except changes shown below
...
var wrapper = OperationWrapper(SomeMethodThatMightThrow);
var exceptionDemoQuery =
from file in files
let n = wrapper(file)
select n;
foreach (var item in exceptionDemoQuery)
{
if (item.Item2 == null)
{
Console.WriteLine("Processing {0}", item.Item1);
}
else
{
// we have exception
Console.WriteLine(item.Item2.Message);
}
}
Console.WriteLine("Press any key to exit");
Console.ReadKey();