Exceptions

An Exception is an error that occurs at runtime when an operation cannot be completed properly. For example:

  • If you try to set the name of a GameObject but do not actually have a reference to one (your reference is null) then it will throw a NullReferenceException.
  • If you have an array with a length of 4 and you try to access the 5th element, it will throw an IndexOutOfRangeException.
  • If you try to load a file that does not exist or write to a file that the operating system has marked as read-only, it will throw an IOException.

You can respond to exceptions using try/catch/finally blocks like so:

try
{
    // Do things that might throw an exception.
    Method1();
    Method2();
    Method3();
}
catch (ExceptionType exception)
{
    // Log the exception if you want to.
    // Or sometimes you might even just ignore it and continue on.
    Debug.LogException(exception);
}
finally
{
    // Do any cleanup that needs to always happen regardless of whether an exception was thrown.
}
  • If Method2 throws an exception, then it will be passed into the catch block and Method3 will not get called.
  • If you do not catch an exception, Unity will catch it and log it in the Console window.
  • You do not need to have both a catch and finally block if you do not need them both.
  • You can have multiple catch blocks for different exception types and you can use the base System.Exception to catch everything.
  • In Visual Studio, if you type try then press Tab twice it will insert a try/catch block.