C# 重新抛出异常
我有以下代码:C# 重新抛出异常,c#,.net,C#,.net,我有以下代码: public static string Get(string requestUri) { try { return GetStringAsync(requestUri).Result; } catch (AggregateException aggregateException) { Console.WriteLine(aggregateException); throw; } }
public static string Get(string requestUri)
{
try
{
return GetStringAsync(requestUri).Result;
}
catch (AggregateException aggregateException)
{
Console.WriteLine(aggregateException);
throw;
}
}
当try块抛出异常时,程序在catch块中按其应该的方式运行,并显示有关错误的信息
问题是,一旦到达重试,调试器将停止并再次引发相同的异常,但处于相同的级别,尽管它应该在堆栈中上升一级
我没有在互联网上找到解决方案,所有示例都与我的代码相对应
编辑
您的解决方案适用于上述代码,但我有另一个解决方案也不适用:
public static string Post(string requestUriString, string s)
{
var request = (HttpWebRequest)WebRequest.Create(requestUriString);
var data = Encoding.ASCII.GetBytes(s);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
try
{
var response = (HttpWebResponse)request.GetResponse();
return new StreamReader(response.GetResponseStream()).ReadToEnd();
}
catch (WebException webException)
{
Console.WriteLine(webException);
throw;
}
}
问题是如何处理聚合异常;将方法更改为
async
方法(这将消除aggregateeexception
wrapper),然后throw
将按预期工作:
public static async Task<string> Get(string requestUri)
{
try
{
return await GetStringAsync(requestUri);
}
catch (Exception exception) // Or, specify the expected exception type
{
Console.WriteLine(exception);
throw; // can be caught in the calling code
}
}
公共静态异步任务Get(字符串requestUri)
{
尝试
{
返回等待GetStringAsync(requestUri);
}
catch(异常)//或者,指定预期的异常类型
{
控制台写入线(例外);
throw;//可以在调用代码中捕获
}
}
您的调试器是否设置为在抛出异常时停止?@Hasan
throw
通常用于catch
块,在该块中,异常将被记录并传播到调用上下文。