ErrObject.Raise(Int32, Object, Object, Object, Object) Método
Definição
Gera um erro em tempo de execução; pode ser usado em vez da instrução Error.Generates a run-time error; can be used instead of the Error statement.
public void Raise (int Number, object? Source = default, object? Description = default, object? HelpFile = default, object? HelpContext = default);
public void Raise (int Number, object Source = default, object Description = default, object HelpFile = default, object HelpContext = default);
member this.Raise : int * obj * obj * obj * obj -> unit
Public Sub Raise (Number As Integer, Optional Source As Object = Nothing, Optional Description As Object = Nothing, Optional HelpFile As Object = Nothing, Optional HelpContext As Object = Nothing)
Parâmetros
- Number
- Int32
Obrigatórios.Required. Long inteiro que identifica a natureza do erro.Long integer that identifies the nature of the error. Os erros do Visual Basic estão no intervalo 0-65535; o intervalo 0-512 é reservado para erros do sistema; o intervalo 513-65535 está disponível para erros definidos pelo usuário.Visual Basic errors are in the range 0-65535; the range 0-512 is reserved for system errors; the range 513-65535 is available for user-defined errors. Ao definir a propriedade Number com seu próprio código de erro em um módulo de classe, você adiciona seu número de código de erro à constante vbObjectError.When setting the Number property to your own error code in a class module, you add your error code number to the vbObjectError constant. Por exemplo, para gerar o erro número 513, atribua vbObjectError + 513 à propriedade Number.For example, to generate the error number 513, assign vbObjectError + 513 to the Number property.
- Source
- Object
Opcional.Optional. String expressão que nomeia o objeto ou aplicativo que gerou o erro.String expression naming the object or application that generated the error. Ao configurar essa propriedade para um objeto, use o formato projeto.classe.When setting this property for an object, use the form project.class. Se Source não for especificado, a ID do processo do projeto atual do Visual Basic será usada.If Source is not specified, the process ID of the current Visual Basic project is used.
- Description
- Object
Opcional.Optional. String expressão que descreve o erro.String expression describing the error. Se não for especificado, o valor na propriedade Number será examinado.If unspecified, the value in the Number property is examined. Se ele pode ser mapeado para um código de erro em tempo de execução do Visual Basic, a cadeia de caracteres que seria retornada pela função Error é usada como a propriedade Description.If it can be mapped to a Visual Basic run-time error code, the string that would be returned by the Error function is used as the Description property. Se não houver nenhum erro do Visual Basic correspondente à propriedade Number, a mensagem "Erro definido pelo aplicativo ou definido pelo objeto" será usada.If there is no Visual Basic error corresponding to the Number property, the "Application-defined or object-defined error" message is used.
- HelpFile
- Object
Opcional.Optional. O caminho totalmente qualificado para o arquivo de Ajuda no qual se pode encontrar ajuda sobre este erro.The fully qualified path to the Help file in which help on this error can be found. Se não for especificado, o Visual Basic usará a unidade totalmente qualificada, o caminho e o nome do arquivo de Ajuda do Visual Basic.If unspecified, Visual Basic uses the fully qualified drive, path, and file name of the Visual Basic Help file.
- HelpContext
- Object
Opcional.Optional. A ID de contexto que identifica um tópico no HelpFile que fornece ajuda para o erro.The context ID identifying a topic within HelpFile that provides help for the error. Se omitida, a ID de contexto do arquivo de Ajuda do Visual Basic para o erro correspondente à propriedade Number será usada, se ela existir.If omitted, the Visual Basic Help-file context ID for the error corresponding to the Number property is used, if it exists.
Exemplos
Este exemplo usa o Err método do objeto Raise para gerar um erro em uma função escrita em Visual Basic.This example uses the Err object's Raise method to generate an error within a function written in Visual Basic. A função de chamada pode capturar o erro e relatá-lo para o usuário com uma caixa de mensagem.The calling function can catch the error and report it to the user with a message box.
Module Module1
Const WidthErrorNumber As Integer = 1000
Const WidthHelpOffset As Object = 100
Sub Main()
CallingProcedure()
End Sub
Sub TestWidth(ByVal width As Integer)
If width > 1000 Then
' Replace HelpFile.hlp with the full path to an appropriate
' help file for the error. Notice that you add the error
' number you want to use to the vbObjectError constant.
' This assures that it will not conflict with a Visual
' Basic error.
Err.Raise(vbObjectError + WidthErrorNumber, "ConsoleApplication1.Module1.TestWidth",
"Width must be less than 1000.", "HelpFile.hlp", WidthHelpOffset)
End If
End Sub
Sub CallingProcedure()
Try
' The error is raised in TestWidth.
TestWidth(2000)
Catch ex As Exception
' The Err object can access a number of pieces of
' information about the error.
Console.WriteLine("Information available from Err object:")
Console.WriteLine(Err.Number)
Console.WriteLine(Err.Description)
Console.WriteLine(Err.Source)
Console.WriteLine(Err.HelpFile)
Console.WriteLine(Err.HelpContext)
Console.WriteLine(Err.GetException)
Console.WriteLine(vbCrLf & "Information available from Exception object:")
Console.WriteLine(ex.Message)
Console.WriteLine(ex.ToString)
Err.Clear()
End Try
End Sub
End Module
' The example produces the following output:
' Information available from Err object:
' -2147220504
' Width must be less than 1000.
' ConsoleApplication1.Module1.TestWidth
' HelpFile.hlp
' 100
' System.Exception: Width must be less than 1000.
' at Microsoft.VisualBasic.ErrObject.Raise(Int32 Number, Object Source, Object
' Description, Object HelpFile, Object HelpContext)
' at ConsoleApplication1.Module1.TestWidth(Int32 width) in C:\Users\example\App
' Data\Local\Temporary Projects\ConsoleApplication1\Module1.vb:line 17
' at ConsoleApplication1.Module1.CallingProcedure() in C:\Users\example\AppData
' \Local\Temporary Projects\ConsoleApplication1\Module1.vb:line 25
'
' Information available from Exception object:
' Width must be less than 1000.
' System.Exception: Width must be less than 1000.
' at Microsoft.VisualBasic.ErrObject.Raise(Int32 Number, Object Source, Object
' Description, Object HelpFile, Object HelpContext)
' at ConsoleApplication1.Module1.TestWidth(Int32 width) in C:\Users\example\App
' Data\Local\Temporary Projects\ConsoleApplication1\Module1.vb:line 17
' at ConsoleApplication1.Module1.CallingProcedure() in C:\Users\example\AppData
' \Local\Temporary Projects\ConsoleApplication1\Module1.vb:line 25
Comentários
Todos os Raise argumentos, exceto, Number são opcionais.All of the Raise arguments except Number are optional. Se você omitir argumentos opcionais e as configurações de Propriedade do Err objeto contiverem valores que não foram limpos, esses valores servirão como os valores para o erro.If you omit optional arguments, and the property settings of the Err object contain values that have not been cleared, those values serve as the values for your error.
Como o Err objeto fornece informações mais sofisticadas do que quando você gera erros com a Error instrução, Raise é útil para gerar erros ao escrever módulos de classe.Because the Err object gives richer information than when you generate errors with the Error statement, Raise is useful for generating errors when writing class modules. Por exemplo, com o Raise método, a origem que gerou o erro pode ser especificada na Source propriedade, a ajuda online para o erro pode ser referenciada e assim por diante.For example, with the Raise method, the source that generated the error can be specified in the Source property, online Help for the error can be referenced, and so on.