Exception Classe
Definizione
Rappresenta gli errori che si verificano durante l'esecuzione dell'applicazione.Represents errors that occur during application execution.
public ref class Exception : System::Runtime::InteropServices::_Exception, System::Runtime::Serialization::ISerializable
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)]
[System.Runtime.InteropServices.ComVisible(true)]
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.AutoDual)]
[System.Serializable]
public class Exception : System.Runtime.InteropServices._Exception, System.Runtime.Serialization.ISerializable
type Exception = class
interface ISerializable
interface _Exception
Public Class Exception
Implements _Exception, ISerializable
- Ereditarietà
-
Exception
- Derivato
- Attributi
- Implementazioni
Esempi
Nell'esempio seguente viene illustrato catch
un blocco definito per la gestione ArithmeticException degli errori.The following example demonstrates a catch
block that is defined to handle ArithmeticException errors. Questo catch
blocco ArithmeticException DivideByZeroException catch
intercetta anche gli DivideByZeroException errori, perché deriva da e non è definito in modo esplicito alcun blocco per gli errori. DivideByZeroExceptionThis catch
block also catches DivideByZeroException errors, because DivideByZeroException derives from ArithmeticException and there is no catch
block explicitly defined for DivideByZeroException errors.
using namespace System;
int main()
{
int x = 0;
try
{
int y = 100 / x;
}
catch ( ArithmeticException^ e )
{
Console::WriteLine( "ArithmeticException Handler: {0}", e );
}
catch ( Exception^ e )
{
Console::WriteLine( "Generic Exception Handler: {0}", e );
}
}
/*
This code example produces the following results:
ArithmeticException Handler: System.DivideByZeroException: Attempted to divide by zero.
at main()
*/
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()
*/
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()
'
Commenti
Questa classe è la classe base per tutte le eccezioni.This class is the base class for all exceptions. Quando si verifica un errore, il sistema o l'applicazione attualmente in esecuzione lo segnala generando un'eccezione che contiene informazioni sull'errore.When an error occurs, either the system or the currently executing application reports it by throwing an exception that contains information about the error. Una volta generata un'eccezione, questa viene gestita dall'applicazione o dal gestore di eccezioni predefinito.After an exception is thrown, it is handled by the application or by the default exception handler.
Contenuto della sezione:In this section:
Errori ed eccezioni Errors and exceptions
Blocchi try/catch Try/catch blocks
Funzionalità del tipo di eccezione Exception type features
Proprietà della classe Exception Exception class properties
Considerazioni sulle prestazioni Performance considerations
Generazione di un'eccezione Re-throwing an exception
Scelta delle eccezioni standard Choosing standard exceptions
Implementazione di eccezioni personalizzateImplementing custom exceptions
Errori ed eccezioniErrors and exceptions
Gli errori di run-time possono verificarsi per diversi motivi.Run-time errors can occur for a variety of reasons. Tuttavia, non tutti gli errori devono essere gestiti come eccezioni nel codice.However, not all errors should be handled as exceptions in your code. Di seguito sono riportate alcune categorie di errori che possono verificarsi in fase di esecuzione e i modi appropriati per rispondervi.Here are some categories of errors that can occur at run time and the appropriate ways to respond to them.
Errori di utilizzo.Usage errors. Un errore di utilizzo rappresenta un errore nella logica del programma che può generare un'eccezione.A usage error represents an error in program logic that can result in an exception. Tuttavia, l'errore non può essere risolto tramite la gestione delle eccezioni, ma modificando il codice difettoso.However, the error should be addressed not through exception handling but by modifying the faulty code. Ad esempio, l'override del Object.Equals(Object) metodo nell'esempio seguente presuppone che l'
obj
argomento debba essere sempre non null.For example, the override of the Object.Equals(Object) method in the following example assumes that theobj
argument must always be non-null.using System; public class Person { 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. Person p = (Person) obj; return this.Name.Equals(p.Name); } } public class Example { public static void Main() { Person p1 = new Person(); p1.Name = "John"; Person p2 = null; // The following throws a NullReferenceException. Console.WriteLine("p1 = p2: {0}", 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 Example 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' NullReferenceException eccezione risultante quando
obj
ènull
può essere eliminata modificando il codice sorgente per testare in modo esplicito il valore null Object.Equals prima di chiamare l'override e quindi ricompilarlo.The NullReferenceException exception that results whenobj
isnull
can be eliminated by modifying the source code to explicitly test for null before calling the Object.Equals override and then re-compiling. L'esempio seguente contiene il codice sorgente corretto che gestisce unnull
argomento.The following example contains the corrected source code that handles anull
argument.using System; public class Person { 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. Person p = obj as Person; if (p == null) return false; else return this.Name.Equals(p.Name); } } public class Example { public static void Main() { Person p1 = new Person(); p1.Name = "John"; Person p2 = null; Console.WriteLine("p1 = p2: {0}", p1.Equals(p2)); } } // The example displays the following output: // p1 = p2: False
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 handles a null obj argument. Dim p As Person = TryCast(obj, Person) If p Is Nothing Then Return False Else Return Me.Name.Equals(p.Name) End If End Function End Class Module Example Public Sub Main() Dim p1 As New Person() p1.Name = "John" Dim p2 As Person = Nothing Console.WriteLine("p1 = p2: {0}", p1.Equals(p2)) End Sub End Module ' The example displays the following output: ' p1 = p2: False
Anziché utilizzare la gestione delle eccezioni per gli errori di utilizzo, è Debug.Assert possibile utilizzare il metodo per identificare gli errori di utilizzo nelle Trace.Assert compilazioni di debug e il metodo per identificare gli errori di utilizzo nelle compilazioni di debug e di rilascio.Instead of using exception handling for usage errors, you can use the Debug.Assert method to identify usage errors in debug builds, and the Trace.Assert method to identify usage errors in both debug and release builds. Per ulteriori informazioni, vedere Asserzioni nel metodo gestito.For more information, see Assertions in Managed Code.
Errori del programma.Program errors. Un errore di programma è un errore di run-time che non può essere necessariamente evitato scrivendo codice privo di bug.A program error is a run-time error that cannot necessarily be avoided by writing bug-free code.
In alcuni casi, un errore del programma può riflettere una condizione di errore prevista o di routine.In some cases, a program error may reflect an expected or routine error condition. In questo caso, è consigliabile evitare di utilizzare la gestione delle eccezioni per gestire l'errore del programma, ma ritentare l'operazione.In this case, you may want to avoid using exception handling to deal with the program error and instead retry the operation. Se, ad esempio, l'utente deve immettere una data in un formato particolare, è possibile analizzare la stringa di data chiamando il DateTime.TryParseExact metodo, che restituisce un Boolean valore che indica se l'operazione di analisi ha avuto esito positivo, anziché utilizzare il parametro DateTime.ParseExactmetodo, che genera un' FormatException eccezione se la stringa di data non può essere convertita in un DateTime valore.For example, if the user is expected to input a date in a particular format, you can parse the date string by calling the DateTime.TryParseExact method, which returns a Boolean value that indicates whether the parse operation succeeded, instead of using the DateTime.ParseExact method, which throws a FormatException exception if the date string cannot be converted to a DateTime value. Analogamente, se un utente tenta di aprire un file che non esiste, è possibile chiamare prima il File.Exists metodo per verificare se il file esiste e, in caso contrario, richiedere all'utente se desidera crearlo.Similarly, if a user tries to open a file that does not exist, you can first call the File.Exists method to check whether the file exists and, if it does not, prompt the user whether he or she wants to create it.
In altri casi, un errore di programma riflette una condizione di errore imprevista che può essere gestita nel codice.In other cases, a program error reflects an unexpected error condition that can be handled in your code. Ad esempio, anche se è stata verificata l'esistenza di un file, è possibile che venga eliminato prima che sia possibile aprirlo oppure che sia danneggiato.For example, even if you've checked to ensure that a file exists, it may be deleted before you can open it, or it may be corrupted. In tal caso, il tentativo di aprire il file creando un'istanza StreamReader di un oggetto o Open chiamando il metodo può FileNotFoundException generare un'eccezione.In that case, trying to open the file by instantiating a StreamReader object or calling the Open method may throw a FileNotFoundException exception. In questi casi, è consigliabile utilizzare la gestione delle eccezioni per correggere l'errore.In these cases, you should use exception handling to recover from the error.
Errori di sistema.System failures. Un errore di sistema è un errore di run-time che non può essere gestito a livello di programmazione in modo significativo.A system failure is a run-time error that cannot be handled programmatically in a meaningful way. Ad esempio, qualsiasi metodo può generare un' OutOfMemoryException eccezione se il Common Language Runtime non è in grado di allocare memoria aggiuntiva.For example, any method can throw an OutOfMemoryException exception if the common language runtime is unable to allocate additional memory. In genere, gli errori di sistema non vengono gestiti mediante la gestione delle eccezioni.Ordinarily, system failures are not handled by using exception handling. In alternativa, è possibile utilizzare un evento, ad esempio AppDomain.UnhandledException , e chiamare il Environment.FailFast metodo per registrare le informazioni sulle eccezioni e notificare all'utente l'errore prima che l'applicazione venga terminata.Instead, you may be able to use an event such as AppDomain.UnhandledException and call the Environment.FailFast method to log exception information and notify the user of the failure before the application terminates.
Blocchi try/catchTry/catch blocks
Il Common Language Runtime fornisce un modello di gestione delle eccezioni basato sulla rappresentazione di eccezioni come oggetti e sulla separazione del codice del programma e del codice di gestione delle try
eccezioni in catch
blocchi e blocchi.The common language runtime provides an exception handling model that is based on the representation of exceptions as objects, and the separation of program code and exception handling code into try
blocks and catch
blocks. Possono essere presenti uno o più catch
blocchi, ognuno progettato per gestire un particolare tipo di eccezione o un blocco progettato per intercettare un'eccezione più specifica rispetto a un altro blocco.There can be one or more catch
blocks, each designed to handle a particular type of exception, or one block designed to catch a more specific exception than another block.
Se un'applicazione gestisce le eccezioni che si verificano durante l'esecuzione di un blocco di codice dell'applicazione, il codice deve try
essere inserito in un'istruzione try
e viene chiamato blocco.If an application handles exceptions that occur during the execution of a block of application code, the code must be placed within a try
statement and is called a try
block. Il codice dell'applicazione che gestisce le eccezioni try
generate da un blocco catch
si trova all'interno di catch
un'istruzione e viene chiamato blocco.Application code that handles exceptions thrown by a try
block is placed within a catch
statement and is called a catch
block. Zero o più catch
blocchi sono associati a un try
blocco e ogni catch
blocco include un filtro di tipo che determina i tipi di eccezioni gestite.Zero or more catch
blocks are associated with a try
block, and each catch
block includes a type filter that determines the types of exceptions it handles.
Quando si verifica un'eccezione in try
un blocco, il sistema cerca i catch
blocchi associati nell'ordine in cui sono visualizzati nel codice dell'applicazione, finché non catch
individua un blocco che gestisce l'eccezione.When an exception occurs in a try
block, the system searches the associated catch
blocks in the order they appear in application code, until it locates a catch
block that handles the exception. Un catch
blocco gestisce un'eccezione di tipo T
se il filtro di tipo del blocco catch specifica T
o qualsiasi tipo che T
deriva da.A catch
block handles an exception of type T
if the type filter of the catch block specifies T
or any type that T
derives from. Il sistema arresta la ricerca dopo aver trovato il catch
primo blocco che gestisce l'eccezione.The system stops searching after it finds the first catch
block that handles the exception. Per questo motivo, nel codice dell'applicazione, catch
un blocco che gestisce un tipo deve essere specificato prima catch
di un blocco che gestisce i tipi di base, come illustrato nell'esempio che segue questa sezione.For this reason, in application code, a catch
block that handles a type must be specified before a catch
block that handles its base types, as demonstrated in the example that follows this section. Un blocco catch che gestisce System.Exception
viene specificato per ultimo.A catch block that handles System.Exception
is specified last.
Se nessuno catch
dei blocchi associati al blocco corrente try
try
gestisce l'eccezione e il blocco corrente è annidato all'interno di altri try
blocchi della chiamata corrente, i catch
blocchi associati alla classe successiva viene eseguita try
la ricerca del blocco di inclusione.If none of the catch
blocks associated with the current try
block handle the exception, and the current try
block is nested within other try
blocks in the current call, the catch
blocks associated with the next enclosing try
block are searched. Se non catch
viene trovato alcun blocco per l'eccezione, il sistema cerca i livelli di nidificazione precedenti nella chiamata corrente.If no catch
block for the exception is found, the system searches previous nesting levels in the current call. Se nella catch
chiamata corrente non viene trovato alcun blocco per l'eccezione, l'eccezione viene passata allo stack di chiamate e il stack frame precedente viene cercato un catch
blocco che gestisce l'eccezione.If no catch
block for the exception is found in the current call, the exception is passed up the call stack, and the previous stack frame is searched for a catch
block that handles the exception. La ricerca dello stack di chiamate continua fino a quando l'eccezione non viene gestita o fino a quando non sono presenti altri frame nello stack di chiamate.The search of the call stack continues until the exception is handled or until no more frames exist on the call stack. Se viene raggiunta la parte superiore dello stack di chiamate senza catch
trovare un blocco che gestisce l'eccezione, il gestore di eccezioni predefinito lo gestisce e l'applicazione termina.If the top of the call stack is reached without finding a catch
block that handles the exception, the default exception handler handles it and the application terminates.
Funzionalità del tipo di eccezioneException type features
I tipi di eccezione supportano le funzionalità seguenti:Exception types support the following features:
Testo leggibile che descrive l'errore.Human-readable text that describes the error. Quando si verifica un'eccezione, il runtime rende disponibile un SMS per informare l'utente della natura dell'errore e suggerire un'azione per la risoluzione del problema.When an exception occurs, the runtime makes a text message available to inform the user of the nature of the error and to suggest action to resolve the problem. Questo messaggio di testo viene mantenuto nella Message proprietà dell'oggetto Exception.This text message is held in the Message property of the exception object. Durante la creazione dell'oggetto eccezione, è possibile passare una stringa di testo al costruttore per descrivere i dettagli di quell'eccezione particolare.During the creation of the exception object, you can pass a text string to the constructor to describe the details of that particular exception. Se al costruttore non viene fornito alcun argomento del messaggio di errore, viene utilizzato il messaggio di errore predefinito.If no error message argument is supplied to the constructor, the default error message is used. Per altre informazioni, vedere la proprietà Message.For more information, see the Message property.
Stato dello stack di chiamate quando è stata generata l'eccezione.The state of the call stack when the exception was thrown. La StackTrace proprietà contiene una traccia dello stack che può essere usata per determinare dove si verifica l'errore nel codice.The StackTrace property carries a stack trace that can be used to determine where the error occurs in the code. L'analisi dello stack elenca tutti i metodi chiamati e i numeri di riga nel file di origine in cui vengono effettuate le chiamate.The stack trace lists all the called methods and the line numbers in the source file where the calls are made.
Proprietà della classe ExceptionException class properties
La Exception classe include numerose proprietà che consentono di identificare la posizione del codice, il tipo, il file della guida e il motivo dell'eccezione: StackTrace, InnerException, Message, HelpLink, HResult, Source, TargetSite, e Data.The Exception class includes a number of properties that help identify the code location, the type, the help file, and the reason for the exception: StackTrace, InnerException, Message, HelpLink, HResult, Source, TargetSite, and Data.
Quando una relazione causale esiste tra due o più eccezioni, InnerException la proprietà gestisce queste informazioni.When a causal relationship exists between two or more exceptions, the InnerException property maintains this information. L'eccezione esterna viene generata in risposta a questa eccezione interna.The outer exception is thrown in response to this inner exception. Il codice che gestisce l'eccezione esterna può utilizzare le informazioni dell'eccezione interna precedente per gestire l'errore in modo più appropriato.The code that handles the outer exception can use the information from the earlier inner exception to handle the error more appropriately. Le informazioni supplementari sull'eccezione possono essere archiviate come una raccolta di coppie chiave/valore nella Data proprietà.Supplementary information about the exception can be stored as a collection of key/value pairs in the Data property.
La stringa del messaggio di errore che viene passata al costruttore durante la creazione dell'oggetto eccezione deve essere localizzata e può essere fornita da un file di risorse tramite ResourceManager la classe.The error message string that is passed to the constructor during the creation of the exception object should be localized and can be supplied from a resource file by using the ResourceManager class. Per ulteriori informazioni sulle risorse localizzate, vedere gli argomenti creazione di assembly satellite e creazione di pacchetti e distribuzione delle risorse .For more information about localized resources, see the Creating Satellite Assemblies and Packaging and Deploying Resources topics.
Per fornire all'utente informazioni dettagliate sul motivo per cui si è verificata HelpLink l'eccezione, la proprietà può conservare un URL (o URN) in un file della guida.To provide the user with extensive information about why the exception occurred, the HelpLink property can hold a URL (or URN) to a help file.
La Exception classe utilizza HRESULT COR_E_EXCEPTION, che ha il valore 0x80131500.The Exception class uses the HRESULT COR_E_EXCEPTION, which has the value 0x80131500.
Per un elenco dei valori iniziali delle proprietà di un'istanza della Exception classe, vedere i Exception costruttori.For a list of initial property values for an instance of the Exception class, see the Exception constructors.
Considerazioni sulle prestazioniPerformance considerations
Generando o gestendo un'eccezione viene utilizzata una quantità significativa di risorse di sistema e tempo di esecuzione.Throwing or handling an exception consumes a significant amount of system resources and execution time. Genera eccezioni solo per gestire condizioni davvero straordinarie, non per gestire eventi stimabili o il controllo di flusso.Throw exceptions only to handle truly extraordinary conditions, not to handle predictable events or flow control. 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.For example, in some cases, such as when you're developing a class library, it's reasonable to throw an exception if a method argument is invalid, because you expect your method to be called with valid parameters. Un argomento di metodo non valido, se non è il risultato di un errore di utilizzo, significa che si è verificato un evento straordinario.An invalid method argument, if it is not the result of a usage error, means that something extraordinary has occurred. Viceversa, non generare un'eccezione se l'input dell'utente non è valido, perché si può prevedere che gli utenti immettano occasionalmente dati non validi.Conversely, do not throw an exception if user input is invalid, because you can expect users to occasionally enter invalid data. Fornire invece un meccanismo di ripetizione dei tentativi in modo che gli utenti possano immettere un input valido.Instead, provide a retry mechanism so users can enter valid input. Né usare eccezioni per gestire gli errori di utilizzo.Nor should you use exceptions to handle usage errors. Usare invece le asserzioni per identificare e correggere gli errori di utilizzo.Instead, use assertions to identify and correct usage errors.
Inoltre, non generare un'eccezione quando un codice restituito è sufficiente. non convertire un codice restituito in un'eccezione; non rilevare periodicamente un'eccezione, ignorarla e continuare l'elaborazione.In addition, do not throw an exception when a return code is sufficient; do not convert a return code to an exception; and do not routinely catch an exception, ignore it, and then continue processing.
Nuova generazione di un'eccezioneRe-throwing an exception
In molti casi, un gestore di eccezioni desidera semplicemente passare l'eccezione al chiamante.In many cases, an exception handler simply wants to pass the exception on to the caller. Questa situazione si verifica in genere in:This most often occurs in:
Libreria di classi che a sua volta esegue il wrapping delle chiamate ai metodi nella libreria di classi .NET Framework o in altre librerie di classi.A class library that in turn wraps calls to methods in the .NET Framework class library or other class libraries.
Applicazione o libreria che rileva un'eccezione irreversibile.An application or library that encounters a fatal exception. Il gestore di eccezioni può registrare l'eccezione e quindi generare nuovamente l'eccezione.The exception handler can log the exception and then re-throw the exception.
Il metodo consigliato per generare di nuovo un'eccezione consiste nell'utilizzare semplicemente l'istruzione throw in C# e l'istruzione throw in Visual Basic senza includere un'espressione.The recommended way to re-throw an exception is to simply use the throw statement in C# and the Throw statement in Visual Basic without including an expression. In questo modo si garantisce che tutte le informazioni sullo stack di chiamate vengano mantenute quando l'eccezione viene propagata al chiamante.This ensures that all call stack information is preserved when the exception is propagated to the caller. Questa condizione è illustrata nell'esempio seguente.The following example illustrates this. Un metodo di estensione di FindOccurrences
stringa,, esegue il wrapping di una String.IndexOf(String, Int32) o più chiamate a senza convalidare i relativi argomenti in anticipo.A string extension method, FindOccurrences
, wraps one or more calls to String.IndexOf(String, Int32) without validating its arguments beforehand.
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
public static class Library
{
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 e) {
// Perform some action here, such as logging this exception.
throw;
}
return indexes.ToArray();
}
}
Imports System.Collections.Generic
Imports System.Runtime.CompilerServices
Public Module Library
<Extension()>
Public Function FindOccurrences(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 FindOccurrences
quindi due volte.A caller then calls FindOccurrences
twice. FindOccurrences
Nella seconda chiamata a, il chiamante null
passa come stringa di ricerca, in cui il String.IndexOf(String, Int32) metodo genera un' ArgumentNullException eccezione.In the second call to FindOccurrences
, the caller passes a null
as the search string, which cases the String.IndexOf(String, Int32) method to throw an ArgumentNullException exception. Questa eccezione viene gestita dal FindOccurrences
metodo e passata di nuovo al chiamante.This exception is handled by the FindOccurrences
method and passed back to the caller. Poiché l'istruzione throw viene utilizzata senza espressioni, l'output dell'esempio mostra che lo stack di chiamate viene mantenuto.Because the throw statement is used with no expression, the output from the example shows that the call stack is preserved.
public class Example
{
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 ({0}) occurred.",
e.GetType().Name);
Console.WriteLine("Message:\n {0}\n", e.Message);
Console.WriteLine("Stack Trace:\n {0}\n", e.StackTrace);
}
}
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()
Module Example
Public Sub Main()
Dim s As String = "It was a cold day when..."
Dim indexes() As Integer = s.FindOccurrences("a")
ShowOccurrences(s, "a", indexes)
Console.WriteLine()
Dim toFind As String = Nothing
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:{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 tramite ilIn contrast, if the exception is re-thrown by using the
throw e;
Throw e
, lo stack di chiamate completo non viene mantenuto e l'esempio genera l'output seguente:statement, the full call stack is not preserved, and the example would generate 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 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.A slightly more cumbersome alternative is to throw a new exception, and to preserve the original exception's call stack information in an inner exception. Il chiamante può quindi usare la InnerException proprietà della nuova eccezione per recuperare stack frame e altre informazioni sull'eccezione originale.The caller can then use the new exception's InnerException property to retrieve stack frame and other information about the original exception. In questo caso, l'istruzione throw è:In this case, the throw statement is:
throw new 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 InnerException proprietà contiene informazioni sull'eccezione originale, come illustrato nel seguente gestore di eccezioni.The user code that handles the exception has to know that the InnerException property contains information about the original exception, as the following exception handler illustrates.
try {
indexes = s.FindOccurrences(toFind);
ShowOccurrences(s, toFind, indexes);
}
catch (ArgumentNullException e) {
Console.WriteLine("An exception ({0}) occurred.",
e.GetType().Name);
Console.WriteLine(" Message:\n{0}", e.Message);
Console.WriteLine(" Stack Trace:\n {0}", e.StackTrace);
Exception ie = e.InnerException;
if (ie != null) {
Console.WriteLine(" The Inner Exception:");
Console.WriteLine(" Exception Name: {0}", ie.GetType().Name);
Console.WriteLine(" Message: {0}\n", ie.Message);
Console.WriteLine(" Stack Trace:\n {0}\n", ie.StackTrace);
}
}
// 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)
Scelta delle eccezioni standardChoosing standard exceptions
Quando è necessario generare un'eccezione, è spesso possibile utilizzare un tipo di eccezione esistente nel .NET Framework anziché implementare un'eccezione personalizzata.When you have to throw an exception, you can often use an existing exception type in the .NET Framework instead of implementing a custom exception. È consigliabile usare un tipo di eccezione standard in queste due condizioni:You should use a standard exception type under these two conditions:
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.You are throwing an exception that is caused by a usage error (that is, by an error in program logic made by the developer who is calling your method). In genere, viene generata un'eccezione, ad ArgumentExceptionesempio ArgumentNullException InvalidOperationException,, o NotSupportedException.Typically, you would throw an exception such as ArgumentException, ArgumentNullException, InvalidOperationException, or NotSupportedException. La stringa fornita al costruttore dell'oggetto Exception quando si crea un'istanza dell'oggetto eccezione dovrebbe descrivere l'errore in modo che lo sviluppatore possa correggerlo.The string you supply to the exception object's constructor when instantiating the exception object should describe the error so that the developer can fix it. Per altre informazioni, vedere la proprietà Message.For more information, see the Message property.
Si sta gestendo un errore che può essere comunicato al chiamante con un'eccezione .NET Framework esistente.You are handling an error that can be communicated to the caller with an existing .NET Framework exception. È consigliabile generare l'eccezione più derivata possibile.You should throw the most derived exception possible. Se, ad esempio, un metodo richiede che un argomento sia un membro valido di un tipo di enumerazione, è necessario InvalidEnumArgumentException generare un'eccezione (la classe più derivata) ArgumentExceptioninvece di un oggetto.For example, if a method requires an argument to be a valid member of an enumeration type, you should throw an InvalidEnumArgumentException (the most derived class) rather than an ArgumentException.
Nella tabella seguente sono elencati i tipi di eccezione comuni e le condizioni in cui vengono generate.The following table lists common exception types and the conditions under which you would throw them.
EccezioneException | CondizioneCondition |
---|---|
ArgumentException | Un argomento non NULL passato a un metodo non è valido.A non-null argument that is passed to a method is invalid. |
ArgumentNullException | Un argomento passato a un metodo è null .An argument that is passed to a method is null . |
ArgumentOutOfRangeException | Un argomento non è compreso nell'intervallo di valori validi.An argument is outside the range of valid values. |
DirectoryNotFoundException | Parte di un percorso di directory non è valida.Part of a directory path is not valid. |
DivideByZeroException | Il denominatore in un'operazione Decimal di divisione o Integer è zero.The denominator in an integer or Decimal division operation is zero. |
DriveNotFoundException | Un'unità non è disponibile o non esiste.A drive is unavailable or does not exist. |
FileNotFoundException | Un file non esiste.A file does not exist. |
FormatException | Un valore non è in un formato appropriato per essere convertito da una stringa tramite un metodo di conversione, Parse ad esempio.A value is not in an appropriate format to be converted from a string by a conversion method such as Parse . |
IndexOutOfRangeException | Un indice non è compreso nei limiti di una matrice o di una raccolta.An index is outside the bounds of an array or collection. |
InvalidOperationException | Una chiamata al metodo non è valida nello stato corrente di un oggetto.A method call is invalid in an object's current state. |
KeyNotFoundException | Impossibile trovare la chiave specificata per l'accesso a un membro in una raccolta.The specified key for accessing a member in a collection cannot be found. |
NotImplementedException | Metodo o operazione non implementata.A method or operation is not implemented. |
NotSupportedException | Un metodo o un'operazione non è supportata.A method or operation is not supported. |
ObjectDisposedException | Viene eseguita un'operazione su un oggetto che è stato eliminato.An operation is performed on an object that has been disposed. |
OverflowException | Un'operazione aritmetica, di cast o di conversione genera un overflow.An arithmetic, casting, or conversion operation results in an overflow. |
PathTooLongException | Un percorso o un nome di file supera la lunghezza massima definita dal sistema.A path or file name exceeds the maximum system-defined length. |
PlatformNotSupportedException | Operazione non supportata nella piattaforma corrente.The operation is not supported on the current platform. |
RankException | Una matrice con un numero errato di dimensioni viene passata a un metodo.An array with the wrong number of dimensions is passed to a method. |
TimeoutException | L'intervallo di tempo assegnato a un'operazione è scaduto.The time interval allotted to an operation has expired. |
UriFormatException | Viene utilizzato un Uniform Resource Identifier non valido (URI).An invalid Uniform Resource Identifier (URI) is used. |
Implementazione di eccezioni personalizzateImplementing custom exceptions
Nei casi seguenti, l'utilizzo di un'eccezione .NET Framework esistente per gestire una condizione di errore non è sufficiente:In the following cases, using an existing .NET Framework exception to handle an error condition is not adequate:
Quando l'eccezione riflette un errore di programma univoco di cui non è possibile eseguire il mapping a un'eccezione .NET Framework esistente.When the exception reflects a unique program error that cannot be mapped to an existing .NET Framework exception.
Quando l'eccezione richiede una gestione diversa dalla gestione appropriata per un'eccezione di .NET Framework esistente, oppure l'eccezione deve essere ambiguità da un'eccezione simile.When the exception requires handling that is different from the handling that is appropriate for an existing .NET Framework exception, or the exception must be disambiguated from a similar exception. Se, ad esempio, si genera ArgumentOutOfRangeException un'eccezione durante l'analisi della rappresentazione numerica di una stringa non compresa nell'intervallo del tipo integrale di destinazione, non si desidera utilizzare la stessa eccezione per un errore risultante dal chiamante che non fornisce il valori vincolati appropriati quando si chiama il metodo.For example, if you throw an ArgumentOutOfRangeException exception when parsing the numeric representation of a string that is out of range of the target integral type, you would not want to use the same exception for an error that results from the caller not supplying the appropriate constrained values when calling the method.
La Exception classe è la classe base di tutte le eccezioni nel .NET Framework.The Exception class is the base class of all exceptions in the .NET Framework. Molte classi derivate si basano sul comportamento ereditato dei membri Exception della classe, non eseguono l'override dei membri Exceptiondi, né definiscono membri univoci.Many derived classes rely on the inherited behavior of the members of the Exception class; they do not override the members of Exception, nor do they define any unique members.
Per definire una classe Exception personalizzata:To define your own exception class:
Definire una classe che eredita da Exception.Define a class that inherits from Exception. Se necessario, definire i membri univoci richiesti dalla classe per fornire informazioni aggiuntive sull'eccezione.If necessary, define any unique members needed by your class to provide additional information about the exception. La ArgumentException classe, ad esempio, include ParamName una proprietà che specifica il nome del parametro il cui argomento ha causato l'eccezione e RegexMatchTimeoutException la proprietà include MatchTimeout una proprietà che indica l'intervallo di timeout.For example, the ArgumentException class includes a ParamName property that specifies the name of the parameter whose argument caused the exception, and the RegexMatchTimeoutException property includes a MatchTimeout property that indicates the time-out interval.
Se necessario, eseguire l'override di tutti i membri ereditati di cui si desidera modificare o modificare la funzionalità.If necessary, override any inherited members whose functionality you want to change or modify. Si noti che la maggior parte delle Exception classi derivate esistenti di non esegue l'override del comportamento dei membri ereditati.Note that most existing derived classes of Exception do not override the behavior of inherited members.
Determinare se l'oggetto eccezione personalizzato è serializzabile.Determine whether your custom exception object is serializable. La serializzazione consente di salvare le informazioni sull'eccezione e consente la condivisione delle informazioni sulle eccezioni da parte di un server e di un proxy client in un contesto remoto.Serialization enables you to save information about the exception and permits exception information to be shared by a server and a client proxy in a remoting context. Per rendere serializzabile l'oggetto eccezione, contrassegnarlo con SerializableAttribute l'attributo.To make the exception object serializable, mark it with the SerializableAttribute attribute.
Definire i costruttori della classe Exception.Define the constructors of your exception class. In genere, le classi di eccezioni hanno uno o più dei costruttori seguenti:Typically, exception classes have one or more of the following constructors:
Exception(), che usa valori predefiniti per inizializzare le proprietà di un nuovo oggetto Exception.Exception(), which uses default values to initialize the properties of a new exception object.
Exception(String), che Inizializza un nuovo oggetto eccezione con un messaggio di errore specificato.Exception(String), which initializes a new exception object with a specified error message.
Exception(String, Exception), che Inizializza un nuovo oggetto eccezione con un messaggio di errore e un'eccezione interna specificati.Exception(String, Exception), which initializes a new exception object with a specified error message and inner exception.
Exception(SerializationInfo, StreamingContext), ovvero un
protected
costruttore che Inizializza un nuovo oggetto eccezione dai dati serializzati.Exception(SerializationInfo, StreamingContext), which is aprotected
constructor that initializes a new exception object from serialized data. È necessario implementare questo costruttore se si è scelto di rendere serializzabile l'oggetto eccezione.You should implement this constructor if you've chosen to make your exception object serializable.
Nell'esempio seguente viene illustrato l'utilizzo di una classe di eccezione personalizzata.The following example illustrates the use of a custom exception class. Definisce un' NotPrimeException
eccezione che viene generata quando un client tenta di recuperare una sequenza di numeri primi specificando un numero iniziale non primario.It defines a NotPrimeException
exception that is thrown when a client tries to retrieve a sequence of prime numbers by specifying a starting number that is not prime. L'eccezione definisce una nuova proprietà, NonPrime
, che restituisce il numero non primo che ha causato l'eccezione.The exception defines a new property, NonPrime
, that returns the non-prime number that caused the exception. Oltre a implementare un costruttore senza parametri protetto e un costruttore SerializationInfo con StreamingContext i parametri e per la NotPrimeException
serializzazione, la classe definisce tre costruttori aggiuntivi NonPrime
per supportare la proprietà.Besides implementing a protected parameterless constructor and a constructor with SerializationInfo and StreamingContext parameters for serialization, the NotPrimeException
class defines three additional constructors to support the NonPrime
property. Ogni costruttore chiama un costruttore della classe base oltre a mantenere il valore del numero non primo.Each constructor calls a base class constructor in addition to preserving the value of the non-prime number. La NotPrimeException
classe viene inoltre contrassegnata con SerializableAttribute l'attributo.The NotPrimeException
class is also marked with the SerializableAttribute attribute.
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; } }
}
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 PrimeNumberGenerator
classe mostrata nell'esempio seguente usa il setaccio di Eratostene per calcolare la sequenza di numeri primi da 2 a un limite specificato dal client nella chiamata al relativo costruttore di classe.The PrimeNumberGenerator
class shown in the following example uses the Sieve of Eratosthenes to calculate the sequence of prime numbers from 2 to a limit specified by the client in the call to its class constructor. Il GetPrimesFrom
metodo restituisce tutti i numeri primi che sono maggiori o uguali al limite inferiore specificato, ma genera un' NotPrimeException
eccezione se tale limite inferiore non è un numero primo.The GetPrimesFrom
method returns all prime numbers that are greater than or equal to a specified lower limit, but throws a NotPrimeException
if that lower limit is not a prime number.
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();
}
}
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
L'esempio seguente esegue due chiamate al metodo GetPrimesFrom
con numeri non primi, uno dei quali supera i limiti del dominio applicazione.The following example makes two calls to the GetPrimesFrom
method with non-prime numbers, one of which crosses application domain boundaries. In entrambi i casi, l'eccezione viene generata e gestita correttamente nel codice client.In both cases, the exception is thrown and successfully handled in client code.
using System;
using System.Reflection;
class Example
{
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 {0} prime numbers from {1} to {2}",
start, limit);
}
catch (NotPrimeException e)
{
Console.WriteLine("{0} is not prime", e.NonPrime);
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("{0} is not prime", e.NonPrime);
Console.WriteLine(e);
Console.WriteLine("--------");
}
}
}
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()
' --------
Windows Runtime e.NET Framework 4.5.1.NET Framework 4.5.1Windows Runtime and .NET Framework 4.5.1.NET Framework 4.5.1
In .NET per app di Windows 8.x Store.NET for Windows 8.x Store apps perWindows 8Windows 8alcune informazioni sulle eccezioni vengono in genere perse quando un'eccezione viene propagata tramite gli stack frame non-.NET Framework.In .NET per app di Windows 8.x Store.NET for Windows 8.x Store apps for Windows 8Windows 8, some exception information is typically lost when an exception is propagated through non-.NET Framework stack frames. A partire da .NET Framework 4.5.1.NET Framework 4.5.1 e Windows 8,1Windows 8.1, il Common Language Runtime continua a usare l'oggetto Exception originale generato a meno che tale eccezione non sia stata modificata in un Framework non-.NET stack frame.Starting with the .NET Framework 4.5.1.NET Framework 4.5.1 and Windows 8,1Windows 8.1, the common language runtime continues to use the original Exception object that was thrown unless that exception was modified in a non-.NET Framework stack frame.
Costruttori
Exception() |
Inizializza una nuova istanza della classe Exception.Initializes a new instance of the Exception class. |
Exception(SerializationInfo, StreamingContext) |
Inizializza una nuova istanza della classe Exception con dati serializzati.Initializes a new instance of the Exception class with serialized data. |
Exception(String) |
Inizializza una nuova istanza della classe Exception con un messaggio di errore specificato.Initializes a new instance of the Exception class with a specified error message. |
Exception(String, Exception) |
Inizializza una nuova istanza della classe Exception con un messaggio di errore specificato e un riferimento all'eccezione interna che è la causa dell'eccezione corrente.Initializes a new instance of the Exception class with a specified error message and a reference to the inner exception that is the cause of this exception. |
Proprietà
Data |
Ottiene una raccolta di coppie chiave-valore che fornisce informazioni aggiuntive definite dall'utente relative all'eccezione.Gets a collection of key/value pairs that provide additional user-defined information about the exception. |
HelpLink |
Ottiene o imposta un collegamento al file della Guida associato all'eccezione.Gets or sets a link to the help file associated with this exception. |
HResult |
Ottiene o imposta HRESULT, un valore numerico codificato che viene assegnato a un'eccezione specifica.Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. |
InnerException |
Ottiene l'istanza di Exception che ha causato l'eccezione corrente.Gets the Exception instance that caused the current exception. |
Message |
Ottiene un messaggio che descrive l'eccezione corrente.Gets a message that describes the current exception. |
Source |
Ottiene o imposta il nome dell'oggetto o dell'applicazione che ha generato l'errore.Gets or sets the name of the application or the object that causes the error. |
StackTrace |
Ottiene una rappresentazione di stringa dei frame immediati nello stack di chiamate.Gets a string representation of the immediate frames on the call stack. |
TargetSite |
Ottiene il metodo che genera l'eccezione corrente.Gets the method that throws the current exception. |
Metodi
Equals(Object) |
Determina se l'oggetto specificato è uguale all'oggetto corrente.Determines whether the specified object is equal to the current object. (Ereditato da Object) |
GetBaseException() |
Se utilizzato come metodo di override in una classe derivata, restituisce l'Exception che è la causa radice di una o più eccezioni successive.When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. |
GetHashCode() |
Funge da funzione hash predefinita.Serves as the default hash function. (Ereditato da Object) |
GetObjectData(SerializationInfo, StreamingContext) |
Quando l'override viene eseguito in una classe derivata, imposta il controllo SerializationInfo per la colonna.When overridden in a derived class, sets the SerializationInfo with information about the exception. |
GetType() |
Ottiene il tipo di runtime dell'istanza corrente.Gets the runtime type of the current instance. |
MemberwiseClone() |
Crea una copia superficiale dell'oggetto Object corrente.Creates a shallow copy of the current Object. (Ereditato da Object) |
ToString() |
Crea e restituisce una rappresentazione di stringa dell'eccezione corrente.Creates and returns a string representation of the current exception. |
Eventi
SerializeObjectState |
Si verifica quando un'eccezione viene serializzata per creare un oggetto di stato eccezione contenente i dati serializzati relativi all'eccezione.Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. |