Cómo: Utilizar excepciones específicas en un bloque Catch
En general, en programación es recomendable detectar un tipo de excepción específico en lugar de usar una instrucción catch
básica.
Cuando se produce una excepción, se pasa a la pila y cada bloque Catch tiene la oportunidad de controlarla. El orden de las instrucciones Catch es importante. Ponga los bloques Catch dirigidos a excepciones específicas antes de un bloque Catch de excepción general o el compilador podría emitir un error. El bloque Catch adecuado se determina haciendo coincidir el tipo de la excepción con el nombre de la excepción especificada en el bloque Catch. Si no hay ningún bloque Catch específico, la excepción se detecta mediante un bloque Catch general, si existe alguno.
En el siguiente ejemplo de código se usa un bloque try
/catch
para detectar una InvalidCastException. El ejemplo crea una clase denominada Employee
con una propiedad única, el nivel de empleado (Emlevel
). Un método, PromoteEmployee
, toma un objeto e incrementa el nivel del empleado. Una InvalidCastException se produce cuando una instancia de DateTime se pasa al método PromoteEmployee
.
using namespace System;
public ref class Employee
{
public:
Employee()
{
emlevel = 0;
}
//Create employee level property.
property int Emlevel
{
int get()
{
return emlevel;
}
void set(int value)
{
emlevel = value;
}
}
private:
int emlevel;
};
public ref class Ex13
{
public:
static void PromoteEmployee(Object^ emp)
{
//Cast object to Employee.
Employee^ e = (Employee^) emp;
// Increment employee level.
e->Emlevel++;
}
static void Main()
{
try
{
Object^ o = gcnew Employee();
DateTime^ newyears = gcnew DateTime(2001, 1, 1);
//Promote the new employee.
PromoteEmployee(o);
//Promote DateTime; results in InvalidCastException as newyears is not an employee instance.
PromoteEmployee(newyears);
}
catch (InvalidCastException^ e)
{
Console::WriteLine("Error passing data to PromoteEmployee method. " + e->Message);
}
}
};
int main()
{
Ex13::Main();
}
using System;
public class Employee
{
//Create employee level property.
public int Emlevel
{
get
{
return(emlevel);
}
set
{
emlevel = value;
}
}
private int emlevel = 0;
}
public class Ex13
{
public static void PromoteEmployee(Object emp)
{
// Cast object to Employee.
var e = (Employee) emp;
// Increment employee level.
e.Emlevel = e.Emlevel + 1;
}
static void Main()
{
try
{
Object o = new Employee();
DateTime newYears = new DateTime(2001, 1, 1);
// Promote the new employee.
PromoteEmployee(o);
// Promote DateTime; results in InvalidCastException as newYears is not an employee instance.
PromoteEmployee(newYears);
}
catch (InvalidCastException e)
{
Console.WriteLine("Error passing data to PromoteEmployee method. " + e.Message);
}
}
}
Public Class Employee
'Create employee level property.
Public Property Emlevel As Integer
Get
Return emlevelValue
End Get
Set
emlevelValue = Value
End Set
End Property
Private emlevelValue As Integer = 0
End Class
Public Class Ex13
Public Shared Sub PromoteEmployee(emp As Object)
' Cast object to Employee.
Dim e As Employee = CType(emp, Employee)
' Increment employee level.
e.Emlevel = e.Emlevel + 1
End Sub
Public Shared Sub Main()
Try
Dim o As Object = New Employee()
Dim newYears As New DateTime(2001, 1, 1)
' Promote the new employee.
PromoteEmployee(o)
' Promote DateTime; results in InvalidCastException as newYears is not an employee instance.
PromoteEmployee(newYears)
Catch e As InvalidCastException
Console.WriteLine("Error passing data to PromoteEmployee method. " + e.Message)
End Try
End Sub
End Class