Back to Blog Home

A Beginner’s Guide to Unity Exception Handling

Yasas Sri Wickramasinghe image

Yasas Sri Wickramasinghe -

A Beginner’s Guide to Unity Exception Handling

Exceptions are the outcomes you do not usually expect in your application. But as a developer, expecting the unexpected is essential to capture exceptions and handle them appropriately. Exception handling is not only applicable to web development projects but also to Unity applications.

This article brings everything you need to know as a beginner to Unity exception handling, including methods to handle exceptions, when to use them, and how to manage exceptions easier using distributed logging.

Introduction to Unity Exception Handling

Exceptions are errors that break your application execution unexpectedly. In Unity development, C# is used for scripting; therefore, it is nice to know the most common C# exceptions you can expect during your Unity application development.

Below are some common exceptions you may encounter in Unity:

Null Reference Exception: occurs when you try to access a variable without a referencing object value during the runtime.

Divide by Zero Exception: occurs when you perform a division where you divide a value by zero.

Out of Memory Exception: occurs if your memory has no sufficient capacity to maintain the program execution.

Index Out of Range Exception: occurs if you try to access an array element or element of a collection with an invalid index value.

Input-Output Exception: occurs if you perform an input-output operation such as reading or writing a file. Any error which blocks the IO operation may trigger this exception.

When there is an exception, Unity shows it as an error in the console. Figure 01 below shows how the Unity console shows such exceptions during the runtime.

You can double-click on the exception to navigate to the code which caused the exception, and it will open in your code editor. Once you find the code block to fix, there are several ways to handle exceptions in Unity.

Logging Unity Exceptions Using Debug.LogException Method

When you want to record a possible exception that you anticipate from a code block, the simplest form to do this is by using Debug.LogException method. This method is more similar to Debug.LogError, but LogException is recommended because it makes your code more readable and works with Unity Cloud Diagnostics.

using System; using UnityEngine; using System.Collections; public class VFXGameController : MonoBehaviour { void VFXControl() { try { // your code segment which might throw an exception } catch (Exception ex) { Debug.LogException(ex, this); } } }

However, you need to carefully use try-catch blocks and exception throwing because it affects the compiler optimizations, making it a complex, time-consuming task. So you must decide whether it needs to throw or catch an exception and implement only when required.

Suppose you have a game logic that is not seriously affecting application security or your primary intended outcome. I suggest using a workaround like the below without using the Debug.LogException method in that scenario.

void checkValue(GameObject obj){ if (obj == null) { Debug.LogError("Game Object is Null"); return; } {

Logging Global Exceptions in a Unity Project

When you have multiple GameObjects in a scene and want to record exceptions, which may arise from different GameObjects, using try-catch blocks and duplicating code logic is not a good approach. It would be best if you set up a global exception logging mechanism in your project.

The easiest and most straightforward way is to create an empty GameObject in your scene and attach a script to it. The script should be especially dedicated to catching possible exceptions from any script attached to any GameObject in the scene. The below example shows a possible approach that you can try in your next Unity project.

using UnityEngine; public class ExceptionManager : MonoBehaviour { void Awake() { Application.logMessageReceived += LogCaughtException; DontDestroyOnLoad(gameObject); } void LogCaughtException(string logText, string stackTrace, LogType logType) { if (logType == LogType.Exception) { // add your exception logging code here } } }

You can log exceptions from a single place by maintaining only one instance of the above ExceptionManager implementation.

You can tweak this implementation slightly based on your need, but make sure to use DontDestroyOnLoad() method to avoid your GameObject getting deleted during a change of scenes.

Distributed Exception Logging Methods

There are several distributed log management services for Unity, but Sentry is the go-to option for many due to its ease of use and state-of-the-art features.

You can set up Sentry easily by following the Getting Started Guide by Sentry. All you need to do is add the below package to Unity and configure it to work with Sentry cloud services.

https://github.com/getsentry/unity.git#0.22.0

In the Sentry dashboard, you can configure automated alerts based on percent-based issue occurrences. This is beneficial in production environments since relevant people will get notifications when something exceeds the defined rule.

Sentry SDK provides the CaptureException method, which synchronizes the triggered exceptions with the Sentry dashboard. The below code segment shows the usage of this method.

void CharactorMovementController() { try { // your game logic which might throw an exception } catch (Exception e) { SentrySdk.CaptureException(e); } }

Once you have integrated Sentry into your project and exceptions are captured, the Sentry dashboard will show all the issues in real-time. If multiple instances of your Unity app are running on various devices, all the issues will be displayed there.

When you have production applications built using Unity and need to monitor them, Sentry's percent-based alerts help you a lot by automating notifications to trigger when a particular exception exceeds the pre-defined threshold; so your development team can prioritize what issue to handle first and maintain the application effectively.

Share

Share on Twitter
Share on Facebook
Share on HackerNews
Share on LinkedIn

Published

Sentry Sign Up CTA

Code breaks, fix it faster

Sign up for Sentry and monitor your application in minutes.

Try Sentry Free

Topics

Guest Posts

New product releases and exclusive demos

Listen to the Syntax Podcast

Of course we sponsor a developer podcast. Check it out on your favorite listening platform.

Listen To Syntax
    TwitterGitHubDribbbleLinkedinDiscord
© 2024 • Sentry is a registered Trademark of Functional Software, Inc.