Hello.
I am using multiple threads in Unity ( mainly for networking, not using UNET ).
When an exception occurs in one of the threads, that aren’t the main unity thread, then I doesn’t get any information/hint about it. It is not showing anything in the editor’s console.
To replicate the problem one could just call the following line of code in your unity application:
This throws an exception in a new Thread. Debug.logs work fine inside different threads, but throwing an exception doesn’t show anything.
I even tried to use try/catch around this line of code, but still doesn’t show anything.
Any ideas?
I never said try/catch doesn’t work. It works within the main thread. But try putting it around the line of code I mentioned in the opening post. Just put “new Thread(()=>{throw new Exception();}).Start();” anywhere in your unity app, so it gets called at some point, you won’t see an exception and that is my problem.
If I put this line of code in a try/catch block then it still does not show an exception.
Ah, yes, that’s actually showing me that an exception was thrown. But why won’t it show something without the try/catch ? Also when I just put throw new Exception(); it shows the exception, even without try/catch. But if an exception occurs on a different thread, then I have to use try/catch? Why?
Also: Thanks for your answer!
because the Console only listens to exceptions on its own thread, as it was designed for. Non-unity threads are outside the scope of its responsibility.
That makes sense and Debug.Log is always linked to the main thread somehow so if I place try/catch around my code in a different thread, then it will be shown in the console?
If you place the try/catch in a different thread it will only show up in that thread. Check the link I posted yesterday, as in that thread you will see a way you can get the exception to show up in the log by manually pushing it to the calling thread.
I also encountered the same issue and I found a solution which uses AppDomain class in .NET.
You can check below sample codes which explains all by itself:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading;
using System;
public class Test : MonoBehaviour {
Thread t1;
List<int> a = null;
void Start ()
{
AppDomain app1 = AppDomain.CurrentDomain
app1.UnhandledException += App1_UnhandledException;
try
{
t1 = new Thread(new ThreadStart(Main1));
t1.Start();
}
catch(Exception e)
{
}
}
private void App1_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Debug.Log(e.ExceptionObject.ToString());
}
void Main1()
{
a.Add(1); // this should cause an expection.
}
private void OnDestroy()
{
try
{
t1.Abort();
}
catch
{
}
}
}