1.我的程式如下:
// Start a Task that throws a NullReferenceException:
Task task = Task.Run(() => { throw null; });
try
{
task.Wait();
}
catch (AggregateException aex)
{
if (aex.InnerException is NullReferenceException)
Console.WriteLine("Null!");
else
throw;
}
2.執行後,出現System.NullReferenceException: 'Object reference not set to an instance of an object.'的訊息.
3.想問的是,為什麼我都用try-catch了,Visual還是出現上面錯誤訊息呢?
............Task不在主執行緒裡錯誤處理.......
O口O
改成這樣吧,抓的到
using System;
using System.Threading;
using System.Threading.Tasks;
public class Example
{
public static async Task Main()
{
try
{
await Task.Run(() => throw new Exception("DoWork failed."));
}
catch (Exception e)
{
Console.WriteLine($"Main exception occurs {e}.");
}
Console.Read();
}
}
App.config也要改
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<runtime>
<ThrowUnobservedTaskExceptions enabled="false" />
</runtime>
</configuration>
別在Debug下執行就抓到了
不好意思,各位先進,我參考的是這本書的範例:C# 5.0 In a Nutshell
P.584,書上寫到,task會由呼叫wait()方法的執行緒throw exception.
可是IDE卻沒有在wait方法那邊處理exception
搞懂了,我一直不知道F5和Ctrl+F5的差別.謝謝指教.^^
VS有提示{ throw null; }
內部Task跳出Exception是正確的, try/catch是包住當前執行緒的Exception, 所以外面那個抓不到.
可以改成這樣, 應該會比較清楚, 會進到裡面那層的try/catch
Task task = Task.Run(() =>
{
try
{
throw null;
}
catch (Exception ex)
{
Console.WriteLine("Task null got it");
throw ex;
}
});
try
{
task.Wait();
}
catch (AggregateException aex)
{
if (aex.InnerException is NullReferenceException)
Console.WriteLine("Null!");
else
throw;
}
測了一下,程式應該是沒什麼問題
thread2
,這時 thread2 等於 1
。thread1
,這時 thread1 等於 3
。throw null
拋出錯誤,由於這段程式區塊是由 task.Wait()
呼叫的,所以會由這裡的 try catch 捕獲。thread3
,由於 task.Wait()
是同步呼叫,thread3 會使用 thread2 的執行續繼續執行,所以 thread3 等於 1
。static void Main(string[] args)
{
Task task = Task.Run(() =>
{
var thread1 = Thread.CurrentThread.ManagedThreadId;
// thread1: 3
throw null;
});
try
{
var thread2 = Thread.CurrentThread.ManagedThreadId;
// thread2: 1
task.Wait();
}
catch (AggregateException aex)
{
var thread3 = Thread.CurrentThread.ManagedThreadId;
// thread3: 1
Console.WriteLine("Null!");
}
}
順便測了 await 呼叫,發現幾個比較有趣的地方,分享一下
AggregateException
,而是 NullReferenceException
,害我有點懷疑人生,想說怎麼沒有 catch 進來,這部分要改成 Exception
才能成功。Task.Run
內的執行續繼續執行,所以 thread3 會等於 3
。static async Task Main(string[] args)
{
Task task = Task.Run(() =>
{
var thread1 = Thread.CurrentThread.ManagedThreadId;
// thread1: 3
throw null;
});
try
{
var thread2 = Thread.CurrentThread.ManagedThreadId;
// thread2: 1
await task;
}
catch (Exception aex)
{
var thread3 = Thread.CurrentThread.ManagedThreadId;
// thread3: 3
Console.WriteLine("Null!");
}
}