Come usare eccezioni specifiche in un blocco catchHow to use specific exceptions in a catch block

In generale, è buona norma intercettare un tipo di eccezione specifico invece che usare un'istruzione catch di base.In general, it's good programming practice to catch a specific type of exception rather than use a basic catch statement.

Quando si verifica un'eccezione, l'eccezione viene passata nello stack e a ogni blocco catch viene data la possibilità di gestirla.When an exception occurs, it is passed up the stack and each catch block is given the opportunity to handle it. L'ordine delle istruzioni catch è importante.The order of catch statements is important. Inserire i blocchi catch per il rilevamento di eccezioni specifiche prima di un blocco catch generale per il rilevamento delle eccezioni per evitare che il compilatore generi un errore.Put catch blocks targeted to specific exceptions before a general exception catch block or the compiler might issue an error. Il blocco catch appropriato viene determinato tramite la corrispondenza del tipo di eccezione al nome dell'eccezione specificato nel blocco catch.The proper catch block is determined by matching the type of the exception to the name of the exception specified in the catch block. Se non è presente alcun blocco catch specifico, l'eccezione viene rilevata da un blocco catch generale, se disponibile.If there is no specific catch block, the exception is caught by a general catch block, if one exists.

L'esempio di codice seguente usa un blocco try/catch per rilevare InvalidCastException.The following code example uses a try/catch block to catch an InvalidCastException. L'esempio crea una classe denominata Employee con un'unica proprietà, il livello del dipendente (Emlevel).The sample creates a class called Employee with a single property, employee level (Emlevel). Il metodo PromoteEmployee accetta un oggetto e incrementa il livello del dipendente.A method, PromoteEmployee, takes an object and increments the employee level. Un'eccezione InvalidCastException si verifica quando viene passata un'istanza di DateTime al metodo PromoteEmployee.An InvalidCastException occurs when a DateTime instance is passed to the PromoteEmployee method.

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;
    }

    public 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

Vedere ancheSee also