Debug.LogError vs Debug.LogException - in which cases?
There are two ways to output errors to console in Unity: Debug.LogError and Debug.LogException. They are almost the same except to the LogError we are passing a string and to the LogException - an Exception. But we can also pass the string to the Exception Constructor. So in what cases should I use them?
For example, if an object is null where it shouldn't be, should I log an error or an exception?
Answer by oscarAbraham · Aug 04, 2021 at 07:20 PM
If you're catching exceptions, you should use LogException. It's practically the same as LogError, but it makes your code clearer. Also LogException works with Unity Cloud Diagnostics.
The thing is, if you can, you might want to avoid throwing an exception. They are slower. Even when not thrown, try/catch blocks make compiler optimizations harder. Usually one depends on exceptions when something exceptional can happen and it's desired to stop execution to prevent awful problems like security breaches. It's about mindsets, though; what do you consider exceptional?
Objects being null is such a common, plausible, scenario, that I usually prefer to keep things running if possible, and I find it better to handle security issues explicitly with code. So, when it's not too dangerous, I put something like if (obj == null) {Debug.LogError("message"); return; }
in my methods. Then, inside that condition, I can put whatever I need to prevent undesired states of the game.
Your answer
Follow this Question
Related Questions
(Solved) Findout if an object exist in the scene, but dont trow exception 1 Answer
File persistence on uninstall (Application.persistentDataPath) 2 Answers
Assertion failed: Assertion failed on expression: 'SUCCEEDED(hr)' 2 Answers
[Best Practice] What's a good way to design multiple steps scenario? 0 Answers
How can I change the alpha value of multicolored text to 0? 1 Answer