Debug.LogError("I am an error through Debug.LogError");
throw new Exception("I am an error through new Exception");
I read that throwing an exception gets handled by Unity and turned into a Debug.LogError message anyway, which is what seems to be the case when i test it.
Is it just a matter of preference or is there a reason to use one over the other?
Debug.LogError() is a UnityEngine method that causes something to appear in Unity’s console.
Throwing an exception is something that can be done when there’s a possibility the code execution enters an unwanted, unsafe path and you want to stop the thread from executing further to prevent further damage.
If an exception is thrown and not caught&handled in the code, the program execution will usually stop and you will be thrown out of the app (back to the operating system).
When you run your code in the Unity editor, the editor catches the thrown errors and does a Debug.LogError() instead of crashing Unity or the app.
When you are debugging a game, it doesn’t really matter which you use. You probably have to get rid of any such situations anyway before you can release the app.
If you are making a library of code for someone else and want them to be able to handle exceptions themselves, then throw an exception
Most of the time they are not the same thing. One obvious difference is, when you throw an exception from a method, rest of the method will not be run and exception will be passed to calling method.
Exceptions are literally for exceptional cases. It means something has gone wrong. When something goes wrong you might want to correct it and continue running, or simply stop running. I can’t know for what purpose you use Exception in your case. But know that LogError will not cause function to quit but throwing Exception will.
There is a difference in handling Exceptions between Android and (for example) iOS applications. When an application encounters an Exception on iOS it usually breaks and closes. However, on Android application continues running - sometimes causing totally unpredictable behaviors. And this might be extremely difficult to test & debug (especially when you are not aware of it).
Think about it the way that exceptions are a part of game functionality but Debug class is a Unity helper class with tools to help the developer who is debugging. In Unity, this is not as clear-cut design as with traditional loggers with log levels etc that are configured on a build/target platform level. Rather its just a simple helper utility.
Exceptions will work regardless of build or platform, whether “Use Player Log” configuration is on or whether the Debug invocations are is wrapped in precompiler condition checks, as recommended by Unity as a best practice.