Este artigo foi traduzido por máquina. Para visualizar o arquivo em inglês, marque a caixa de seleção Inglês. Você também pode exibir o texto Em inglês em uma janela pop-up, movendo o ponteiro do mouse sobre o texto.
Tradução
Inglês

Exception Classe

Representa os erros que ocorrem durante a execução do aplicativo.

Namespace:  System
Assembly:  mscorlib (em mscorlib. dll)

[SerializableAttribute]
[ComVisibleAttribute(true)]
[ClassInterfaceAttribute(ClassInterfaceType.None)]
public class Exception : ISerializable, _Exception

Classe This is the classe base for Tudo Exceptions.When an Error Occurs, Either the sistema or the aplicativo currently Executing Reports IT by an exceção containing informações throwing Sobre the error.Once thrown, an Exceção is Handled by the aplicativo or by the usar como padrão Exceção manipulador.

Tente-catch blocos

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, respectively.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.

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.Application code within a try statement is a try block.Application code that handles exceptions thrown by a try block is placed within a catch statement, and is called a catch block.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.

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.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.The system stops searching after it finds the first catch block that handles the exception.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.A catch block that handles System.Exception is specified last.

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.If no catch block for the exception is found, the system searches previous nesting levels in the current call.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.The pesquisa of the pilha de chamadas continues until the exceção is Handled or until no more Quadros exist on the pilha de chamadas.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.

Recursos Tipo de exceção

Tipos de exceção suportar os recursos a seguir:

  • Texto legível que descreve o erro.When an occurs, the Tempo de execução makes a to inform the of the Nature of the error and to suggest to resolver the problem.This text message is held in the Message property of the exception object.During the creation of the objeto exceção, you can transmitir a text Cadeia de Caracteres to the construtor to Describe the Details of that exceção particular.If Sem erros argumento mensagem is supplied to the construtor, the mensagem Error usar como padrão is used.

  • The estado of the pilha de chamadas when the exceção was Descartado.The StackTrace property carries a stack trace that can be used to determine where in the code the error occurs.The rastreamento de pilha Lists All the chamado Methods, and the Linha numbers in the arquivo origem where the Calls are made.

Exceção tipo categorias

Two categories of exceptions exist under the base class Exception:

Propriedades da Classe Exception

Exception 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.

When a causal relationship exists between two or more exceptions, the InnerException property maintains this information.Is the outer exceção Descartado in resposta to this exceção INNER.O código que manipula a exceção externa pode usar as informações da exceção interna anteriormente para manipular o erro mais adequadamente.Supplementary information about the exception can be stored in the Data property.

The error message string passed to the constructor during the creation of the exception object should be localized, and can be supplied from a resource file using the ResourceManager.For more information on localized resources, see the System.Resources namespace overview and Compactação e implantação de recursos.

To provide the user with extensive information concerning why the exception occurred, the HelpLink property can hold a URL (or URN) to a help file.

Exception uses the HRESULT COR_E_EXCEPTION, which has the value 0x80131500.

For a list of initial property values for an instance of Exception, see the Exception constructors.

Considerações sobre desempenho

Uma quantidade significativa de recursos do sistema e tempo de execução são usadas quando você acionar ou manipular uma exceção.Throw Exceptions only to conditions truly extraordinary identificador, not to Events predictable identificador or fluxo Controlar.For exemplo, Your Aplicativo can reasonably lançar an exceção if a argumento método is inválido because you expect to chamar Your método with válido Parameters.Um argumento inválido método significa que algo extraordinária ocorreu.Conversely, not Gerar uma Exceção if is because you can expect users to occasionally ENTER .In such a maiúsculas e minúsculas, Provide a Repetir Mechanism SO Users can Enter válido entrada.

Throw Exceptions only for conditions extraordinary, then Exceptions in a Purpose General that applies to the Majority of Your Aplicativo, not a that applies to a Specific .Os fundamentos para essa abordagem é que a maioria dos erros podem ser tratadas por validação e código de proximidade ao erro; manipulação de erros No exceção needs To be Descartado or caught.The Geral Purpose manipulador de exceção catches truly unexpected Exceptions thrown Anywhere in the aplicativo.

Além disso, faça não lançar uma exceção quando um retorno Código é suficiente; not Converter a código de retorno to an exceção; AND NOT routinely capturar an exceção, ignorar IT, then Continuar processamento.

The following code example demonstrates a catch block that is defined to handle ArithmeticException errors.This catch block also catches DivideByZeroException errors because DivideByZeroException derives from ArithmeticException, and there is no catch block explicitly defined for DivideByZeroException errors.

using System;

class ExceptionTestClass 
{
   public static void Main() 
   {
      int x = 0;
      try 
      {
         int y = 100/x;
      }
         catch (ArithmeticException e) 
         {
            Console.WriteLine("ArithmeticException Handler: {0}", e.ToString());
         }
         catch (Exception e) 
         {
            Console.WriteLine("Generic Exception Handler: {0}", e.ToString());
         }
   }	
}
/*
This code example produces the following results:

ArithmeticException Handler: System.DivideByZeroException: Attempted to divide by zero.
   at ExceptionTestClass.Main()

*/


import System.*;

class ExceptionTestClass
{
    public static void main(String[] args)
    {
        int x = 0;
        try {
            int y = 100 / x;
        }
        catch (ArithmeticException e) {
            Console.WriteLine("ArithmeticException Handler: {0}", e.ToString());
        }
        catch (System.Exception e) {
            Console.WriteLine("Generic Exception Handler: {0}", e.ToString());
        }
    } //main
} //ExceptionTestClass


System.Object
  System.Exception
    Microsoft.Build.BuildEngine.InternalLoggerException
    Microsoft.Build.BuildEngine.InvalidProjectFileException
    Microsoft.Build.Framework.LoggerException
    Microsoft.JScript.CmdLineException
    Microsoft.JScript.ParserException
    Microsoft.VisualBasic.ApplicationServices.CantStartSingleInstanceException
    Microsoft.VisualBasic.ApplicationServices.NoStartupFormException
    Microsoft.VisualBasic.Compatibility.VB6.WebClassContainingClassNotOptional
    Microsoft.VisualBasic.Compatibility.VB6.WebClassCouldNotFindEvent
    Microsoft.VisualBasic.Compatibility.VB6.WebClassNextItemCannotBeCurrentWebItem
    Microsoft.VisualBasic.Compatibility.VB6.WebClassNextItemRespondNotFound
    Microsoft.VisualBasic.Compatibility.VB6.WebClassUserWebClassNameNotOptional
    Microsoft.VisualBasic.Compatibility.VB6.WebClassWebClassFileNameNotOptional
    Microsoft.VisualBasic.Compatibility.VB6.WebClassWebItemNotValid
    Microsoft.VisualBasic.Compatibility.VB6.WebItemAssociatedWebClassNotOptional
    Microsoft.VisualBasic.Compatibility.VB6.WebItemClosingTagNotFound
    Microsoft.VisualBasic.Compatibility.VB6.WebItemCouldNotLoadEmbeddedResource
    Microsoft.VisualBasic.Compatibility.VB6.WebItemCouldNotLoadTemplateFile
    Microsoft.VisualBasic.Compatibility.VB6.WebItemNameNotOptional
    Microsoft.VisualBasic.Compatibility.VB6.WebItemNoTemplateSpecified
    Microsoft.VisualBasic.Compatibility.VB6.WebItemTooManyNestedTags
    Microsoft.VisualBasic.Compatibility.VB6.WebItemUnexpectedErrorReadingTemplateFile
    Microsoft.VisualBasic.CompilerServices.IncompleteInitialization
    Microsoft.VisualBasic.CompilerServices.InternalErrorException
    Microsoft.VisualBasic.FileIO.MalformedLineException
    System.ApplicationException
    System.ComponentModel.Design.ExceptionCollection
    System.Configuration.Provider.ProviderException
    System.Configuration.SettingsPropertyIsReadOnlyException
    System.Configuration.SettingsPropertyNotFoundException
    System.Configuration.SettingsPropertyWrongTypeException
    System.DirectoryServices.ActiveDirectory.ActiveDirectoryObjectExistsException
    System.DirectoryServices.ActiveDirectory.ActiveDirectoryObjectNotFoundException
    System.DirectoryServices.ActiveDirectory.ActiveDirectoryOperationException
    System.DirectoryServices.ActiveDirectory.ActiveDirectoryServerDownException
    System.DirectoryServices.Protocols.DirectoryException
    System.IO.IsolatedStorage.IsolatedStorageException
    System.Net.Mail.SmtpException
    System.Runtime.CompilerServices.RuntimeWrappedException
    System.Runtime.Remoting.MetadataServices.SUDSGeneratorException
    System.Runtime.Remoting.MetadataServices.SUDSParserException
    System.SystemException
    System.Web.Security.MembershipCreateUserException
    System.Web.Security.MembershipPasswordException
    System.Web.UI.ViewStateException
    System.Windows.Forms.AxHost.InvalidActiveXStateException

Quaisquer membros públicos estático (compartilhados na Visual Basic) desse tipo são Thread seguro. Não há garantia de que qualquer membro de instância seja isento de segmentos.

Contribuições da comunidade

ADICIONAR
Mostrar: