Una excepción es un error que ocurre durante la ejecución del programa.
try-catch permite manejar algunos errores sin que el flujo termine inmediatamente.
try
{
int numero = int.Parse("hola");
}
catch
{
Debug.Log("Ocurrió un error");
}
try
{
int numero = int.Parse("hola");
}
catch (Exception error)
{
Debug.Log(error.Message);
}
Necesita:
using System;
Podemos capturar únicamente cierto tipo de error.
try
{
int numero = int.Parse(texto);
}
catch (FormatException)
{
Debug.Log("El formato no es válido");
}
Se ejecuta haya ocurrido un error o no.
try
{
Debug.Log("Intentando");
}
catch
{
Debug.Log("Error");
}
finally
{
Debug.Log("Fin");
}
Permite lanzar una excepción manualmente.