Nota
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare ad accedere o modificare le directory.
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare a modificare le directory.
Questo articolo fornisce osservazioni supplementari alla documentazione di riferimento per questa API.
La classe Exception è la classe base per tutte le eccezioni. Quando si verifica un errore, il sistema o l'applicazione attualmente in esecuzione lo segnala generando un'eccezione che contiene informazioni sull'errore. Dopo la generazione di un'eccezione, viene gestita dall'applicazione o dal gestore eccezioni predefinito.
Errori ed eccezioni
Gli errori di runtime possono verificarsi per diversi motivi. Tuttavia, non tutti gli errori devono essere gestiti come eccezioni nel codice. Ecco alcune categorie di errori che possono verificarsi in fase di esecuzione e i modi appropriati per rispondere a tali errori.
Errori di utilizzo. Un errore di utilizzo rappresenta un errore nella logica del programma che può generare un'eccezione. Tuttavia, l'errore deve essere risolto non tramite la gestione delle eccezioni, ma modificando il codice difettoso. Ad esempio, l'override del metodo Object.Equals(Object) nell'esempio seguente presuppone che l'argomento
obj
sia sempre diverso da Null.using System; public class Person1 { private string _name; public string Name { get { return _name; } set { _name = value; } } public override int GetHashCode() { return this.Name.GetHashCode(); } public override bool Equals(object obj) { // This implementation contains an error in program logic: // It assumes that the obj argument is not null. Person1 p = (Person1) obj; return this.Name.Equals(p.Name); } } public class UsageErrorsEx1 { public static void Main() { Person1 p1 = new Person1(); p1.Name = "John"; Person1 p2 = null; // The following throws a NullReferenceException. Console.WriteLine($"p1 = p2: {p1.Equals(p2)}"); } }
// In F#, null is not a valid state for declared types // without 'AllowNullLiteralAttribute' [<AllowNullLiteral>] type Person() = member val Name = "" with get, set override this.GetHashCode() = this.Name.GetHashCode() override this.Equals(obj) = // This implementation contains an error in program logic: // It assumes that the obj argument is not null. let p = obj :?> Person this.Name.Equals p.Name let p1 = Person() p1.Name <- "John" let p2: Person = null // The following throws a NullReferenceException. printfn $"p1 = p2: {p1.Equals p2}"
Public Class Person Private _name As String Public Property Name As String Get Return _name End Get Set _name = value End Set End Property Public Overrides Function Equals(obj As Object) As Boolean ' This implementation contains an error in program logic: ' It assumes that the obj argument is not null. Dim p As Person = CType(obj, Person) Return Me.Name.Equals(p.Name) End Function End Class Module Example2 Public Sub Main() Dim p1 As New Person() p1.Name = "John" Dim p2 As Person = Nothing ' The following throws a NullReferenceException. Console.WriteLine("p1 = p2: {0}", p1.Equals(p2)) End Sub End Module
L'eccezione NullReferenceException che restituisce quando
obj
ènull
può essere eliminata modificando il codice sorgente in modo da testare in modo esplicito i valori Null prima di chiamare l'override Object.Equals e quindi ripetere la compilazione. L'esempio seguente contiene il codice sorgente corretto che gestisce un argomentonull
.using System; public class Person2 { private string _name; public string Name { get { return _name; } set { _name = value; } } public override int GetHashCode() { return this.Name.GetHashCode(); } public override bool Equals(object obj) { // This implementation handles a null obj argument. Person2 p = obj as Person2; if (p == null) return false; else return this.Name.Equals(p.Name); } } public class UsageErrorsEx2 { public static void Main() { Person2 p1 = new Person2(); p1.Name = "John"; Person2 p2 = null; Console.WriteLine($"p1 = p2: {p1.Equals(p2)}"); } } // The example displays the following output: // p1 = p2: False
// In F#, null is not a valid state for declared types // without 'AllowNullLiteralAttribute' [<AllowNullLiteral>] type Person() = member val Name = "" with get, set override this.GetHashCode() = this.Name.GetHashCode() override this.Equals(obj) = // This implementation handles a null obj argument. match obj with | :? Person as p -> this.Name.Equals p.Name | _ -> false let p1 = Person() p1.Name <- "John" let p2: Person = null printfn $"p1 = p2: {p1.Equals p2}" // The example displays the following output: // p1 = p2: False
Public Class Person2 Private _name As String Public Property Name As String Get Return _name End Get Set _name = Value End Set End Property Public Overrides Function Equals(obj As Object) As Boolean ' This implementation handles a null obj argument. Dim p As Person2 = TryCast(obj, Person2) If p Is Nothing Then Return False Else Return Me.Name.Equals(p.Name) End If End Function End Class Module Example3 Public Sub Main() Dim p1 As New Person2() p1.Name = "John" Dim p2 As Person2 = Nothing Console.WriteLine("p1 = p2: {0}", p1.Equals(p2)) End Sub End Module ' The example displays the following output: ' p1 = p2: False
Anziché usare la gestione delle eccezioni per gli errori di utilizzo, è possibile usare il metodo Debug.Assert per identificare gli errori di utilizzo nelle compilazioni di debug e il metodo Trace.Assert per identificare gli errori di utilizzo nelle compilazioni di debug e versione. Per altre informazioni, vedere Asserzioni nel Codice Gestito.
Errori del programma. Un errore di programma è un errore di run-time che non può essere necessariamente evitato scrivendo codice privo di bug.
In alcuni casi, un errore del programma può riflettere una condizione di errore prevista o di routine. In questo caso, è consigliabile evitare di usare la gestione delle eccezioni per gestire l'errore del programma e ripetere l'operazione. Ad esempio, se si prevede che l'utente inserisca una data in un formato specifico, è possibile analizzare la stringa di data chiamando il metodo DateTime.TryParseExact, che restituisce un valore Boolean che indica se l'operazione di analisi è riuscita, anziché usare il metodo DateTime.ParseExact, che genera un'eccezione FormatException se la stringa di data non può essere convertita in un valore DateTime. Analogamente, se un utente tenta di aprire un file che non esiste, è prima possibile chiamare il metodo File.Exists per verificare se il file esiste e, in caso contrario, chiedere all'utente se vuole crearlo.
In altri casi, un errore del programma riflette una condizione di errore imprevista che può essere gestita nel codice. Ad esempio, anche se è stato controllato per assicurarsi che esista un file, potrebbe essere eliminato prima di poterlo aprire oppure potrebbe essere danneggiato. In tal caso, il tentativo di aprire il file creando un'istanza di un oggetto StreamReader o chiamando il metodo Open può generare un'eccezione FileNotFoundException. In questi casi, è consigliabile usare la gestione delle eccezioni per il ripristino dall'errore.
Errori di sistema. Un errore di sistema è un errore di runtime che non può essere gestito a livello di codice in modo significativo. Ad esempio, qualsiasi metodo può generare un'eccezione OutOfMemoryException se Common Language Runtime non è in grado di allocare memoria aggiuntiva. In genere, gli errori di sistema non vengono gestiti tramite la gestione delle eccezioni. Potrebbe invece essere possibile usare un evento come AppDomain.UnhandledException e chiamare il metodo Environment.FailFast per registrare le informazioni sulle eccezioni e notificare all'utente l'errore prima che l'applicazione termini.
Blocchi try/catch
Common Language Runtime fornisce un modello di gestione delle eccezioni basato sulla rappresentazione delle eccezioni come oggetti e sulla separazione del codice del programma e della gestione delle eccezioni in blocchi try
e blocchi catch
. Possono essere presenti uno o più blocchi catch
, ognuno progettato per gestire un determinato tipo di eccezione o un blocco progettato per intercettare un'eccezione più specifica rispetto a un altro blocco.
Se un'applicazione gestisce le eccezioni che si verificano durante l'esecuzione di un blocco di codice dell'applicazione, il codice deve essere inserito all'interno di un'istruzione try
e viene chiamato blocco try
. Il codice dell'applicazione che gestisce le eccezioni generate da un blocco try
viene inserito all'interno di un'istruzione catch
e viene chiamato blocco catch
. Zero o più blocchi catch
sono associati a un blocco try
e ogni blocco catch
include un filtro di tipo che determina i tipi di eccezioni gestite.
Quando si verifica un'eccezione in un blocco di try
, il sistema cerca i blocchi di catch
associati nell'ordine in cui vengono visualizzati nel codice dell'applicazione finché non individua un blocco catch
che gestisce l'eccezione. Un blocco catch
gestisce un'eccezione di tipo T
se il filtro di tipo del blocco catch specifica T
o qualsiasi tipo da cui T
deriva. Il sistema smette di eseguire la ricerca dopo aver trovato il primo blocco catch
che gestisce l'eccezione. Per questo motivo, nel codice dell'applicazione, un blocco catch
che gestisce un tipo deve essere specificato prima di un blocco catch
che gestisce i relativi tipi di base, come illustrato nell'esempio che segue questa sezione. Un blocco catch che gestisce System.Exception
è specificato per ultimo.
Se nessuno dei blocchi di catch
associati all'try
blocco corrente gestisce l'eccezione e il blocco try
corrente viene annidato all'interno di altri blocchi di try
nella chiamata corrente, vengono cercati i blocchi catch
associati al blocco di inclusione successivo try
. Se non viene trovato alcun blocco catch
per l'eccezione, il sistema cerca i livelli di annidamento precedenti nella chiamata corrente. Se non viene trovato alcun blocco catch
per l'eccezione nella chiamata corrente, l'eccezione viene passata allo stack di chiamate e viene eseguita la ricerca di un blocco dello stack catch
precedente che gestisce l'eccezione. La ricerca dello stack di chiamate continua fino a quando l'eccezione non viene gestita o fino a quando non esistono più frame nello stack di chiamate. Se viene raggiunta la parte superiore dello stack di chiamate senza trovare un blocco catch
che gestisce l'eccezione, il gestore di eccezioni predefinito lo gestisce e l'applicazione termina.
F# try.. con expression
F# non usa blocchi catch
. Al contrario, un'eccezione generata viene confrontata con un singolo blocco with
. Poiché si tratta di un'espressione, anziché di una dichiarazione, tutti i percorsi devono restituire lo stesso tipo. Per altre informazioni, vedere Il tentativo... con Expression.
Caratteristiche del tipo di eccezione
I tipi di eccezione supportano le funzionalità seguenti:
Testo leggibile che descrive l'errore. Quando si verifica un'eccezione, il runtime rende disponibile un sms per informare l'utente della natura dell'errore e suggerire un'azione per risolvere il problema. Questo messaggio di testo viene mantenuto nella proprietà Message dell'oggetto eccezione. Durante la creazione dell'oggetto eccezione, è possibile passare una stringa di testo al costruttore per descrivere i dettagli di tale eccezione specifica. Se non viene fornito alcun argomento del messaggio di errore al costruttore, viene utilizzato il messaggio di errore predefinito. Per ulteriori informazioni, consultare la proprietà Message.
Stato dello stack di chiamate quando è stata generata l'eccezione. La proprietà StackTrace contiene un'analisi dello stack che può essere usata per determinare dove si verifica l'errore nel codice. L'analisi dello stack elenca tutti i metodi chiamati e i numeri di riga nel file di origine in cui vengono effettuate le chiamate.
Proprietà della classe di eccezione
La classe Exception include una serie di proprietà che consentono di identificare il percorso del codice, il tipo, il file della Guida e il motivo dell'eccezione: StackTrace, InnerException, Message, HelpLink, HResult, Source, TargetSitee Data.
Quando esiste una relazione causale tra due o più eccezioni, la proprietà InnerException gestisce queste informazioni. L'eccezione esterna viene generata in risposta a questa eccezione interna. Il codice che gestisce l'eccezione esterna può usare le informazioni dell'eccezione interna precedente per gestire l'errore in modo più appropriato. Le informazioni supplementari sull'eccezione possono essere archiviate come raccolta di coppie chiave/valore nella proprietà Data.
La stringa del messaggio di errore passata al costruttore durante la creazione dell'oggetto eccezione deve essere localizzata e può essere fornita da un file di risorse usando la classe ResourceManager. Per altre informazioni sulle risorse localizzate, vedere gli argomenti Creating Satellite Assemblies e Packaging and Deploying Resources .
Per fornire all'utente informazioni complete sul motivo per cui si è verificata l'eccezione, la proprietà HelpLink può contenere un URL (o URN) a un file della Guida.
La classe Exception usa l'COR_E_EXCEPTION
HRESULT , che ha il valore 0x80131500.
Per un elenco dei valori iniziali delle proprietà per un'istanza della classe Exception, vedere i costruttori Exception.
Considerazioni sulle prestazioni
La generazione o la gestione di un'eccezione utilizza una quantità significativa di risorse di sistema e tempo di esecuzione. Genera eccezioni solo per gestire condizioni davvero straordinarie, non per gestire eventi prevedibili o controllo del flusso. Ad esempio, in alcuni casi, ad esempio quando si sviluppa una libreria di classi, è ragionevole generare un'eccezione se un argomento del metodo non è valido, perché si prevede che il metodo venga chiamato con parametri validi. Un argomento del metodo non valido, se non è il risultato di un errore di utilizzo, significa che si è verificato un evento straordinario. Viceversa, non generare un'eccezione se l'input dell'utente non è valido, perché è possibile prevedere che gli utenti immettano occasionalmente dati non validi. Fornire invece un meccanismo di ripetizione dei tentativi in modo che gli utenti possano immettere un input valido. Né è consigliabile usare le eccezioni per gestire gli errori di utilizzo. Usare invece asserzioni per identificare e correggere gli errori di utilizzo.
Inoltre, non generare un'eccezione quando un codice restituito è sufficiente; non convertire un codice restituito in un'eccezione; e non intercettare regolarmente un'eccezione, ignorarla e quindi continuare l'elaborazione.
Generare nuovamente un'eccezione
In molti casi, un gestore eccezioni vuole semplicemente passare l'eccezione al chiamante. Questo avviene più spesso in:
Libreria di classi che a sua volta esegue il wrapping delle chiamate ai metodi nella libreria di classi .NET o in altre librerie di classi.
Applicazione o libreria che rileva un'eccezione irreversibile. Il gestore eccezioni può registrare l'eccezione e quindi generare nuovamente l'eccezione.
Il modo consigliato per generare nuovamente un'eccezione consiste nell'usare semplicemente l'istruzione throw in C#, la reraise funzione in F# e l'istruzione Throw in Visual Basic senza includere un'espressione. In questo modo, tutte le informazioni sullo stack di chiamate vengono mantenute quando l'eccezione viene propagata al chiamante. Nell'esempio seguente viene illustrato questo. Un metodo di estensione stringa, FindOccurrences
, incapsula una o più chiamate a String.IndexOf(String, Int32) senza convalidare preventivamente i suoi argomenti.
using System;
using System.Collections.Generic;
public static class Library1
{
public static int[] FindOccurrences(this String s, String f)
{
var indexes = new List<int>();
int currentIndex = 0;
try
{
while (currentIndex >= 0 && currentIndex < s.Length)
{
currentIndex = s.IndexOf(f, currentIndex);
if (currentIndex >= 0)
{
indexes.Add(currentIndex);
currentIndex++;
}
}
}
catch (ArgumentNullException)
{
// Perform some action here, such as logging this exception.
throw;
}
return indexes.ToArray();
}
}
open System
module Library =
let findOccurrences (s: string) (f: string) =
let indexes = ResizeArray()
let mutable currentIndex = 0
try
while currentIndex >= 0 && currentIndex < s.Length do
currentIndex <- s.IndexOf(f, currentIndex)
if currentIndex >= 0 then
indexes.Add currentIndex
currentIndex <- currentIndex + 1
with :? ArgumentNullException ->
// Perform some action here, such as logging this exception.
reraise ()
indexes.ToArray()
Imports System.Collections.Generic
Imports System.Runtime.CompilerServices
Public Module Library
<Extension()>
Public Function FindOccurrences1(s As String, f As String) As Integer()
Dim indexes As New List(Of Integer)
Dim currentIndex As Integer = 0
Try
Do While currentIndex >= 0 And currentIndex < s.Length
currentIndex = s.IndexOf(f, currentIndex)
If currentIndex >= 0 Then
indexes.Add(currentIndex)
currentIndex += 1
End If
Loop
Catch e As ArgumentNullException
' Perform some action here, such as logging this exception.
Throw
End Try
Return indexes.ToArray()
End Function
End Module
Un chiamante chiama quindi FindOccurrences
due volte. Nella seconda chiamata a FindOccurrences
, il chiamante passa un null
come stringa di ricerca, che fa sì che il metodo String.IndexOf(String, Int32) generi un'eccezione ArgumentNullException. Questa eccezione viene gestita dal metodo FindOccurrences
e restituita al chiamante. Poiché l'istruzione throw viene usata senza espressione, l'output dell'esempio mostra che lo stack di chiamate viene mantenuto.
public class RethrowEx1
{
public static void Main()
{
String s = "It was a cold day when...";
int[] indexes = s.FindOccurrences("a");
ShowOccurrences(s, "a", indexes);
Console.WriteLine();
String toFind = null;
try
{
indexes = s.FindOccurrences(toFind);
ShowOccurrences(s, toFind, indexes);
}
catch (ArgumentNullException e)
{
Console.WriteLine($"An exception ({e.GetType().Name}) occurred.");
Console.WriteLine($"Message:{Environment.NewLine} {e.Message}{Environment.NewLine}");
Console.WriteLine($"Stack Trace:{Environment.NewLine} {e.StackTrace}{Environment.NewLine}");
}
}
private static void ShowOccurrences(String s, String toFind, int[] indexes)
{
Console.Write("'{0}' occurs at the following character positions: ",
toFind);
for (int ctr = 0; ctr < indexes.Length; ctr++)
Console.Write("{0}{1}", indexes[ctr],
ctr == indexes.Length - 1 ? "" : ", ");
Console.WriteLine();
}
}
// The example displays the following output:
// 'a' occurs at the following character positions: 4, 7, 15
//
// An exception (ArgumentNullException) occurred.
// Message:
// Value cannot be null.
// Parameter name: value
//
// Stack Trace:
// at System.String.IndexOf(String value, Int32 startIndex, Int32 count, Stri
// ngComparison comparisonType)
// at Library.FindOccurrences(String s, String f)
// at Example.Main()
open Library
let showOccurrences toFind (indexes: int[]) =
printf $"'{toFind}' occurs at the following character positions: "
for i = 0 to indexes.Length - 1 do
printf $"""{indexes[i]}{if i = indexes.Length - 1 then "" else ", "}"""
printfn ""
let s = "It was a cold day when..."
let indexes = findOccurrences s "a"
showOccurrences "a" indexes
printfn ""
let toFind: string = null
try
let indexes = findOccurrences s toFind
showOccurrences toFind indexes
with :? ArgumentNullException as e ->
printfn $"An exception ({e.GetType().Name}) occurred."
printfn $"Message:\n {e.Message}\n"
printfn $"Stack Trace:\n {e.StackTrace}\n"
// The example displays the following output:
// 'a' occurs at the following character positions: 4, 7, 15
//
// An exception (ArgumentNullException) occurred.
// Message:
// Value cannot be null. (Parameter 'value')
//
// Stack Trace:
// at System.String.IndexOf(String value, Int32 startIndex, Int32 count, Stri
// ngComparison comparisonType)
// at Library.findOccurrences(String s, String f)
// at <StartupCode$fs>.main@()
Module Example1
Public Sub Main()
Dim s As String = "It was a cold day when..."
Dim indexes() As Integer = s.FindOccurrences1("a")
ShowOccurrences(s, "a", indexes)
Console.WriteLine()
Dim toFind As String = Nothing
Try
indexes = s.FindOccurrences1(toFind)
ShowOccurrences(s, toFind, indexes)
Catch e As ArgumentNullException
Console.WriteLine("An exception ({0}) occurred.",
e.GetType().Name)
Console.WriteLine("Message:{0} {1}{0}", vbCrLf, e.Message)
Console.WriteLine("Stack Trace:{0} {1}{0}", vbCrLf, e.StackTrace)
End Try
End Sub
Private Sub ShowOccurrences(s As String, toFind As String, indexes As Integer())
Console.Write("'{0}' occurs at the following character positions: ",
toFind)
For ctr As Integer = 0 To indexes.Length - 1
Console.Write("{0}{1}", indexes(ctr),
If(ctr = indexes.Length - 1, "", ", "))
Next
Console.WriteLine()
End Sub
End Module
' The example displays the following output:
' 'a' occurs at the following character positions: 4, 7, 15
'
' An exception (ArgumentNullException) occurred.
' Message:
' Value cannot be null.
' Parameter name: value
'
' Stack Trace:
' at System.String.IndexOf(String value, Int32 startIndex, Int32 count, Stri
' ngComparison comparisonType)
' at Library.FindOccurrences(String s, String f)
' at Example.Main()
Al contrario, se l'eccezione viene generata nuovamente usando questa istruzione:
throw e;
Throw e
raise e
... quindi lo stack di chiamate completo non viene mantenuto e l'esempio genera l'output seguente:
'a' occurs at the following character positions: 4, 7, 15
An exception (ArgumentNullException) occurred.
Message:
Value cannot be null.
Parameter name: value
Stack Trace:
at Library.FindOccurrences(String s, String f)
at Example.Main()
Un'alternativa leggermente più complessa consiste nel generare una nuova eccezione e mantenere le informazioni sullo stack di chiamate dell'eccezione originale in un'eccezione interna. Il chiamante può quindi usare la proprietà InnerException della nuova eccezione per recuperare lo stack frame e altre informazioni sull'eccezione originale. In questo caso, l'istruzione throw è:
throw new ArgumentNullException("You must supply a search string.", e);
raise (ArgumentNullException("You must supply a search string.", e) )
Throw New ArgumentNullException("You must supply a search string.",
e)
Il codice utente che gestisce l'eccezione deve sapere che la proprietà InnerException contiene informazioni sull'eccezione originale, come illustrato dal gestore eccezioni seguente.
try
{
indexes = s.FindOccurrences(toFind);
ShowOccurrences(s, toFind, indexes);
}
catch (ArgumentNullException e)
{
Console.WriteLine($"An exception ({e.GetType().Name}) occurred.");
Console.WriteLine($" Message:{Environment.NewLine}{e.Message}");
Console.WriteLine($" Stack Trace:{Environment.NewLine} {e.StackTrace}");
Exception ie = e.InnerException;
if (ie != null)
{
Console.WriteLine(" The Inner Exception:");
Console.WriteLine($" Exception Name: {ie.GetType().Name}");
Console.WriteLine($" Message: {ie.Message}{Environment.NewLine}");
Console.WriteLine($" Stack Trace:{Environment.NewLine} {ie.StackTrace}{Environment.NewLine}");
}
}
// The example displays the following output:
// 'a' occurs at the following character positions: 4, 7, 15
//
// An exception (ArgumentNullException) occurred.
// Message: You must supply a search string.
//
// Stack Trace:
// at Library.FindOccurrences(String s, String f)
// at Example.Main()
//
// The Inner Exception:
// Exception Name: ArgumentNullException
// Message: Value cannot be null.
// Parameter name: value
//
// Stack Trace:
// at System.String.IndexOf(String value, Int32 startIndex, Int32 count, Stri
// ngComparison comparisonType)
// at Library.FindOccurrences(String s, String f)
try
let indexes = findOccurrences s toFind
showOccurrences toFind indexes
with :? ArgumentNullException as e ->
printfn $"An exception ({e.GetType().Name}) occurred."
printfn $" Message:\n{e.Message}"
printfn $" Stack Trace:\n {e.StackTrace}"
let ie = e.InnerException
if ie <> null then
printfn " The Inner Exception:"
printfn $" Exception Name: {ie.GetType().Name}"
printfn $" Message: {ie.Message}\n"
printfn $" Stack Trace:\n {ie.StackTrace}\n"
// The example displays the following output:
// 'a' occurs at the following character positions: 4, 7, 15
//
// An exception (ArgumentNullException) occurred.
// Message: You must supply a search string.
//
// Stack Trace:
// at Library.FindOccurrences(String s, String f)
// at Example.Main()
//
// The Inner Exception:
// Exception Name: ArgumentNullException
// Message: Value cannot be null.
// Parameter name: value
//
// Stack Trace:
// at System.String.IndexOf(String value, Int32 startIndex, Int32 count, Stri
// ngComparison comparisonType)
// at Library.FindOccurrences(String s, String f)
Try
indexes = s.FindOccurrences(toFind)
ShowOccurrences(s, toFind, indexes)
Catch e As ArgumentNullException
Console.WriteLine("An exception ({0}) occurred.",
e.GetType().Name)
Console.WriteLine(" Message: {1}{0}", vbCrLf, e.Message)
Console.WriteLine(" Stack Trace:{0} {1}{0}", vbCrLf, e.StackTrace)
Dim ie As Exception = e.InnerException
If ie IsNot Nothing Then
Console.WriteLine(" The Inner Exception:")
Console.WriteLine(" Exception Name: {0}", ie.GetType().Name)
Console.WriteLine(" Message: {1}{0}", vbCrLf, ie.Message)
Console.WriteLine(" Stack Trace:{0} {1}{0}", vbCrLf, ie.StackTrace)
End If
End Try
' The example displays the following output:
' 'a' occurs at the following character positions: 4, 7, 15
'
' An exception (ArgumentNullException) occurred.
' Message: You must supply a search string.
'
' Stack Trace:
' at Library.FindOccurrences(String s, String f)
' at Example.Main()
'
' The Inner Exception:
' Exception Name: ArgumentNullException
' Message: Value cannot be null.
' Parameter name: value
'
' Stack Trace:
' at System.String.IndexOf(String value, Int32 startIndex, Int32 count, Stri
' ngComparison comparisonType)
' at Library.FindOccurrences(String s, String f)
Scegliere le eccezioni standard
Quando è necessario generare un'eccezione, è spesso possibile usare un tipo di eccezione esistente in .NET anziché implementare un'eccezione personalizzata. È consigliabile usare un tipo di eccezione standard in queste due condizioni:
Si sta generando un'eccezione causata da un errore di utilizzo, ovvero da un errore nella logica del programma eseguita dallo sviluppatore che chiama il metodo . In genere, si genera un'eccezione, ad esempio ArgumentException, ArgumentNullException, InvalidOperationExceptiono NotSupportedException. La stringa specificata al costruttore dell'oggetto eccezione durante la creazione di un'istanza dell'oggetto eccezione deve descrivere l'errore in modo che lo sviluppatore possa correggerlo. Per ulteriori informazioni, consultare la proprietà Message.
Stai gestendo un errore che può essere comunicato al chiamante con un'eccezione .NET esistente. È consigliabile generare l'eccezione più derivata possibile. Ad esempio, se un metodo richiede che un argomento sia un membro valido di un tipo di enumerazione, è necessario generare un InvalidEnumArgumentException (la classe più derivata) anziché un ArgumentException.
Nella tabella seguente sono elencati i tipi di eccezione comuni e le condizioni in cui vengono generate.
Eccezione | Condizione |
---|---|
ArgumentException | Un argomento non NULL passato a un metodo non è valido. |
ArgumentNullException | Un argomento passato a un metodo è null . |
ArgumentOutOfRangeException | Un argomento non rientra nell'intervallo di valori validi. |
DirectoryNotFoundException | Una parte del percorso della directory non è valida. |
DivideByZeroException | Il denominatore in un'operazione di divisione intera o Decimal è zero. |
DriveNotFoundException | Un disco non è disponibile o non esiste. |
FileNotFoundException | Un file non esiste. |
FormatException | Un valore non è in un formato appropriato per essere convertito da una stringa tramite un metodo di conversione, come ad esempio Parse . |
IndexOutOfRangeException | Un indice non rientra nei limiti di una matrice o di una raccolta. |
InvalidOperationException | Una chiamata al metodo non è valida nello stato corrente di un oggetto. |
KeyNotFoundException | Impossibile trovare la chiave specificata per l'accesso a un membro in una raccolta. |
NotImplementedException | Un metodo o un'operazione non viene implementato. |
NotSupportedException | Un metodo o un'operazione non è supportato. |
ObjectDisposedException | Un'operazione viene eseguita su un oggetto scartato. |
OverflowException | Un'operazione aritmetica, di cast o di conversione comporta un overflow. |
PathTooLongException | Un percorso o un nome di file supera la lunghezza massima definita dal sistema. |
PlatformNotSupportedException | L'operazione non è supportata nella piattaforma corrente. |
RankException | Una matrice con il numero errato di dimensioni viene passata a un metodo. |
TimeoutException | L'intervallo di tempo assegnato a un'operazione è scaduto. |
UriFormatException | Viene usato un URI (Uniform Resource Identifier) non valido. |
Implementare eccezioni personalizzate
Nei casi seguenti, l'uso di un'eccezione .NET esistente per gestire una condizione di errore non è adeguata:
Quando l'eccezione riflette un errore di programma univoco che non può essere mappato a un'eccezione .NET esistente.
Quando l'eccezione richiede la gestione diversa dalla gestione appropriata per un'eccezione .NET esistente oppure l'eccezione deve essere disambiguata da un'eccezione simile. Ad esempio, se si genera un'eccezione ArgumentOutOfRangeException durante l'analisi della rappresentazione numerica di una stringa che non rientra nell'intervallo del tipo integrale di destinazione, non si vuole usare la stessa eccezione per un errore risultante dal chiamante che non fornisce i valori vincolati appropriati quando si chiama il metodo .
La classe Exception è la classe base di tutte le eccezioni in .NET. Molte classi derivate si basano sul comportamento ereditato dei membri della classe Exception; non eseguono l'override dei membri di Exceptionné definiscono membri univoci.
Per definire la propria classe di eccezione:
Definire una classe che eredita da Exception. Se necessario, definire eventuali membri univoci necessari per la classe per fornire informazioni aggiuntive sull'eccezione. Ad esempio, la classe ArgumentException include una proprietà ParamName che specifica il nome del parametro il cui argomento ha causato l'eccezione e la proprietà RegexMatchTimeoutException include una proprietà MatchTimeout che indica l'intervallo di timeout.
Se necessario, eseguire l'override dei membri ereditati la cui funzionalità si desidera cambiare o modificare. Si noti che la maggior parte delle classi derivate attuali di Exception non sovrascrivono il comportamento dei membri ereditati.
Determinare se l'oggetto eccezione personalizzato è serializzabile. La serializzazione consente di salvare informazioni sull'eccezione e di consentire la condivisione delle informazioni sulle eccezioni da parte di un server e di un proxy client in un contesto di comunicazione remota. Per rendere serializzabile l'oggetto eccezione, contrassegnarlo con l'attributo SerializableAttribute.
Definisci i costruttori della tua classe di eccezione. In genere, le classi di eccezioni hanno uno o più costruttori seguenti:
Exception(), che usa i valori predefiniti per inizializzare le proprietà di un nuovo oggetto eccezione.
Exception(String), che inizializza un nuovo oggetto eccezione con un messaggio di errore specificato.
Exception(String, Exception), che inizializza un nuovo oggetto eccezione con un messaggio di errore e un'eccezione interna specificati.
Exception(SerializationInfo, StreamingContext), ovvero un costruttore
protected
che inizializza un nuovo oggetto eccezione dai dati serializzati. È consigliabile implementare questo costruttore se si è scelto di rendere serializzabile l'oggetto eccezione.
Nell'esempio seguente viene illustrato l'uso di una classe di eccezione personalizzata. Definisce un'eccezione NotPrimeException
generata quando un client tenta di recuperare una sequenza di numeri primi specificando un numero iniziale che non è primo. L'eccezione definisce una nuova proprietà, NonPrime
, che restituisce il numero non primo che ha causato l'eccezione. Oltre a implementare un costruttore senza parametri protetto e un costruttore con parametri SerializationInfo e StreamingContext per la serializzazione, la classe NotPrimeException
definisce tre costruttori aggiuntivi per supportare la proprietà NonPrime
. Ogni costruttore chiama un costruttore della classe base e, allo stesso tempo, preserva il valore del numero non primo. La classe NotPrimeException
viene contrassegnata anche con l'attributo SerializableAttribute.
using System;
using System.Runtime.Serialization;
[Serializable()]
public class NotPrimeException : Exception
{
private int notAPrime;
protected NotPrimeException()
: base()
{ }
public NotPrimeException(int value) :
base(String.Format("{0} is not a prime number.", value))
{
notAPrime = value;
}
public NotPrimeException(int value, string message)
: base(message)
{
notAPrime = value;
}
public NotPrimeException(int value, string message, Exception innerException) :
base(message, innerException)
{
notAPrime = value;
}
protected NotPrimeException(SerializationInfo info,
StreamingContext context)
: base(info, context)
{ }
public int NonPrime
{ get { return notAPrime; } }
}
namespace global
open System
open System.Runtime.Serialization
[<Serializable>]
type NotPrimeException =
inherit Exception
val notAPrime: int
member this.NonPrime =
this.notAPrime
new (value) =
{ inherit Exception($"%i{value} is not a prime number."); notAPrime = value }
new (value, message) =
{ inherit Exception(message); notAPrime = value }
new (value, message, innerException: Exception) =
{ inherit Exception(message, innerException); notAPrime = value }
// F# does not support protected members
new () =
{ inherit Exception(); notAPrime = 0 }
new (info: SerializationInfo, context: StreamingContext) =
{ inherit Exception(info, context); notAPrime = 0 }
Imports System.Runtime.Serialization
<Serializable()> _
Public Class NotPrimeException : Inherits Exception
Private notAPrime As Integer
Protected Sub New()
MyBase.New()
End Sub
Public Sub New(value As Integer)
MyBase.New(String.Format("{0} is not a prime number.", value))
notAPrime = value
End Sub
Public Sub New(value As Integer, message As String)
MyBase.New(message)
notAPrime = value
End Sub
Public Sub New(value As Integer, message As String, innerException As Exception)
MyBase.New(message, innerException)
notAPrime = value
End Sub
Protected Sub New(info As SerializationInfo,
context As StreamingContext)
MyBase.New(info, context)
End Sub
Public ReadOnly Property NonPrime As Integer
Get
Return notAPrime
End Get
End Property
End Class
La classe PrimeNumberGenerator
illustrata nell'esempio seguente usa il Sieve di Eratosthenes per calcolare la sequenza di numeri primi da 2 a un limite specificato dal client nella chiamata al relativo costruttore di classe. Il metodo GetPrimesFrom
restituisce tutti i numeri primi maggiori o uguali a un limite inferiore specificato, ma genera un NotPrimeException
se tale limite inferiore non è un numero primo.
using System;
using System.Collections.Generic;
[Serializable]
public class PrimeNumberGenerator
{
private const int START = 2;
private int maxUpperBound = 10000000;
private int upperBound;
private bool[] primeTable;
private List<int> primes = new List<int>();
public PrimeNumberGenerator(int upperBound)
{
if (upperBound > maxUpperBound)
{
string message = String.Format(
"{0} exceeds the maximum upper bound of {1}.",
upperBound, maxUpperBound);
throw new ArgumentOutOfRangeException(message);
}
this.upperBound = upperBound;
// Create array and mark 0, 1 as not prime (True).
primeTable = new bool[upperBound + 1];
primeTable[0] = true;
primeTable[1] = true;
// Use Sieve of Eratosthenes to determine prime numbers.
for (int ctr = START; ctr <= (int)Math.Ceiling(Math.Sqrt(upperBound));
ctr++)
{
if (primeTable[ctr]) continue;
for (int multiplier = ctr; multiplier <= upperBound / ctr; multiplier++)
if (ctr * multiplier <= upperBound) primeTable[ctr * multiplier] = true;
}
// Populate array with prime number information.
int index = START;
while (index != -1)
{
index = Array.FindIndex(primeTable, index, (flag) => !flag);
if (index >= 1)
{
primes.Add(index);
index++;
}
}
}
public int[] GetAllPrimes()
{
return primes.ToArray();
}
public int[] GetPrimesFrom(int prime)
{
int start = primes.FindIndex((value) => value == prime);
if (start < 0)
throw new NotPrimeException(prime, String.Format("{0} is not a prime number.", prime));
else
return primes.FindAll((value) => value >= prime).ToArray();
}
}
namespace global
open System
[<Serializable>]
type PrimeNumberGenerator(upperBound) =
let start = 2
let maxUpperBound = 10000000
let primes = ResizeArray()
let primeTable =
upperBound + 1
|> Array.zeroCreate<bool>
do
if upperBound > maxUpperBound then
let message = $"{upperBound} exceeds the maximum upper bound of {maxUpperBound}."
raise (ArgumentOutOfRangeException message)
// Create array and mark 0, 1 as not prime (True).
primeTable[0] <- true
primeTable[1] <- true
// Use Sieve of Eratosthenes to determine prime numbers.
for i = start to float upperBound |> sqrt |> ceil |> int do
if not primeTable[i] then
for multiplier = i to upperBound / i do
if i * multiplier <= upperBound then
primeTable[i * multiplier] <- true
// Populate array with prime number information.
let mutable index = start
while index <> -1 do
index <- Array.FindIndex(primeTable, index, fun flag -> not flag)
if index >= 1 then
primes.Add index
index <- index + 1
member _.GetAllPrimes() =
primes.ToArray()
member _.GetPrimesFrom(prime) =
let start =
Seq.findIndex ((=) prime) primes
if start < 0 then
raise (NotPrimeException(prime, $"{prime} is not a prime number.") )
else
Seq.filter ((>=) prime) primes
|> Seq.toArray
Imports System.Collections.Generic
<Serializable()> Public Class PrimeNumberGenerator
Private Const START As Integer = 2
Private maxUpperBound As Integer = 10000000
Private upperBound As Integer
Private primeTable() As Boolean
Private primes As New List(Of Integer)
Public Sub New(upperBound As Integer)
If upperBound > maxUpperBound Then
Dim message As String = String.Format(
"{0} exceeds the maximum upper bound of {1}.",
upperBound, maxUpperBound)
Throw New ArgumentOutOfRangeException(message)
End If
Me.upperBound = upperBound
' Create array and mark 0, 1 as not prime (True).
ReDim primeTable(upperBound)
primeTable(0) = True
primeTable(1) = True
' Use Sieve of Eratosthenes to determine prime numbers.
For ctr As Integer = START To CInt(Math.Ceiling(Math.Sqrt(upperBound)))
If primeTable(ctr) Then Continue For
For multiplier As Integer = ctr To CInt(upperBound \ ctr)
If ctr * multiplier <= upperBound Then primeTable(ctr * multiplier) = True
Next
Next
' Populate array with prime number information.
Dim index As Integer = START
Do While index <> -1
index = Array.FindIndex(primeTable, index, Function(flag)
Return Not flag
End Function)
If index >= 1 Then
primes.Add(index)
index += 1
End If
Loop
End Sub
Public Function GetAllPrimes() As Integer()
Return primes.ToArray()
End Function
Public Function GetPrimesFrom(prime As Integer) As Integer()
Dim start As Integer = primes.FindIndex(Function(value)
Return value = prime
End Function)
If start < 0 Then
Throw New NotPrimeException(prime, String.Format("{0} is not a prime number.", prime))
Else
Return primes.FindAll(Function(value)
Return value >= prime
End Function).ToArray()
End If
End Function
End Class
Nell'esempio seguente vengono effettuate due chiamate al metodo GetPrimesFrom
con numeri non primi, uno dei quali supera i limiti del dominio applicazione. In entrambi i casi, l'eccezione viene generata e gestita correttamente nel codice client.
using System;
using System.Reflection;
class Example1
{
public static void Main()
{
int limit = 10000000;
PrimeNumberGenerator primes = new PrimeNumberGenerator(limit);
int start = 1000001;
try
{
int[] values = primes.GetPrimesFrom(start);
Console.WriteLine($"There are {start} prime numbers from {limit} to {2}");
}
catch (NotPrimeException e)
{
Console.WriteLine($"{e.NonPrime} is not prime");
Console.WriteLine(e);
Console.WriteLine("--------");
}
AppDomain domain = AppDomain.CreateDomain("Domain2");
PrimeNumberGenerator gen = (PrimeNumberGenerator)domain.CreateInstanceAndUnwrap(
typeof(Example).Assembly.FullName,
"PrimeNumberGenerator", true,
BindingFlags.Default, null,
new object[] { 1000000 }, null, null);
try
{
start = 100;
Console.WriteLine(gen.GetPrimesFrom(start));
}
catch (NotPrimeException e)
{
Console.WriteLine($"{e.NonPrime} is not prime");
Console.WriteLine(e);
Console.WriteLine("--------");
}
}
}
open System
open System.Reflection
let limit = 10000000
let primes = PrimeNumberGenerator limit
let start = 1000001
try
let values = primes.GetPrimesFrom start
printfn $"There are {values.Length} prime numbers from {start} to {limit}"
with :? NotPrimeException as e ->
printfn $"{e.NonPrime} is not prime"
printfn $"{e}"
printfn "--------"
let domain = AppDomain.CreateDomain "Domain2"
let gen =
domain.CreateInstanceAndUnwrap(
typeof<PrimeNumberGenerator>.Assembly.FullName,
"PrimeNumberGenerator", true,
BindingFlags.Default, null,
[| box 1000000 |], null, null)
:?> PrimeNumberGenerator
try
let start = 100
printfn $"{gen.GetPrimesFrom start}"
with :? NotPrimeException as e ->
printfn $"{e.NonPrime} is not prime"
printfn $"{e}"
printfn "--------"
Imports System.Reflection
Module Example
Sub Main()
Dim limit As Integer = 10000000
Dim primes As New PrimeNumberGenerator(limit)
Dim start As Integer = 1000001
Try
Dim values() As Integer = primes.GetPrimesFrom(start)
Console.WriteLine("There are {0} prime numbers from {1} to {2}",
start, limit)
Catch e As NotPrimeException
Console.WriteLine("{0} is not prime", e.NonPrime)
Console.WriteLine(e)
Console.WriteLine("--------")
End Try
Dim domain As AppDomain = AppDomain.CreateDomain("Domain2")
Dim gen As PrimeNumberGenerator = domain.CreateInstanceAndUnwrap(
GetType(Example).Assembly.FullName,
"PrimeNumberGenerator", True,
BindingFlags.Default, Nothing,
{1000000}, Nothing, Nothing)
Try
start = 100
Console.WriteLine(gen.GetPrimesFrom(start))
Catch e As NotPrimeException
Console.WriteLine("{0} is not prime", e.NonPrime)
Console.WriteLine(e)
Console.WriteLine("--------")
End Try
End Sub
End Module
' The example displays the following output:
' 1000001 is not prime
' NotPrimeException: 1000001 is not a prime number.
' at PrimeNumberGenerator.GetPrimesFrom(Int32 prime)
' at Example.Main()
' --------
' 100 is not prime
' NotPrimeException: 100 is not a prime number.
' at PrimeNumberGenerator.GetPrimesFrom(Int32 prime)
' at Example.Main()
' --------
Esempi
Nell'esempio seguente viene illustrato un blocco catch
(with
in F#) definito per gestire gli errori ArithmeticException. Questo blocco di catch
rileva anche gli errori di DivideByZeroException, perché DivideByZeroException deriva da ArithmeticException e non esiste alcun blocco di catch
definito in modo esplicito per gli errori di DivideByZeroException.
using System;
class ExceptionTestClass
{
public static void Main()
{
int x = 0;
try
{
int y = 100 / x;
}
catch (ArithmeticException e)
{
Console.WriteLine($"ArithmeticException Handler: {e}");
}
catch (Exception e)
{
Console.WriteLine($"Generic Exception Handler: {e}");
}
}
}
/*
This code example produces the following results:
ArithmeticException Handler: System.DivideByZeroException: Attempted to divide by zero.
at ExceptionTestClass.Main()
*/
module ExceptionTestModule
open System
let x = 0
try
let y = 100 / x
()
with
| :? ArithmeticException as e ->
printfn $"ArithmeticException Handler: {e}"
| e ->
printfn $"Generic Exception Handler: {e}"
// This code example produces the following results:
// ArithmeticException Handler: System.DivideByZeroException: Attempted to divide by zero.
// at <StartupCode$fs>.$ExceptionTestModule.main@()
Class ExceptionTestClass
Public Shared Sub Main()
Dim x As Integer = 0
Try
Dim y As Integer = 100 / x
Catch e As ArithmeticException
Console.WriteLine("ArithmeticException Handler: {0}", e.ToString())
Catch e As Exception
Console.WriteLine("Generic Exception Handler: {0}", e.ToString())
End Try
End Sub
End Class
'
'This code example produces the following results:
'
'ArithmeticException Handler: System.OverflowException: Arithmetic operation resulted in an overflow.
' at ExceptionTestClass.Main()
'