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 aGameObject
but do not actually have a reference to one (your reference isnull
) then it will throw aNullReferenceException
. - 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 thecatch
block andMethod3
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
andfinally
block if you do not need them both. - You can have multiple
catch
blocks for different exception types and you can use the baseSystem.Exception
to catch everything. - In Visual Studio, if you type
try
then pressTab
twice it will insert atry/catch
block.