Exception.ToString Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Cria e devolve uma representação string da exceção atual.
public:
override System::String ^ ToString();
public override string ToString();
override this.ToString : unit -> string
Public Overrides Function ToString () As String
Devoluções
Uma representação em cadeia da exceção atual.
Implementações
Exemplos
O exemplo seguinte causa uma exceção e mostra o resultado de invocar ToString essa exceção. Note que o Exception.ToString método é chamado implicitamente quando a instância da classe Exception aparece na lista de argumentos do Console.WriteLine método.
using System;
public class TestClass
{}
public class Example
{
public static void Main()
{
var test = new TestClass();
Object[] objectsToCompare = { test, test.ToString(), 123,
123.ToString(), "some text",
"Some Text" };
string s = "some text";
foreach (var objectToCompare in objectsToCompare) {
try {
int i = s.CompareTo(objectToCompare);
Console.WriteLine("Comparing '{0}' with '{1}': {2}",
s, objectToCompare, i);
}
catch (ArgumentException e) {
Console.WriteLine("Bad argument: {0} (type {1})",
objectToCompare,
objectToCompare.GetType().Name);
Console.WriteLine("Exception information: {0}", e);
}
Console.WriteLine();
}
}
}
// The example displays the following output:
// Bad argument: TestClass (type TestClass)
// Exception information: System.ArgumentException: Object must be of type String.
// at System.String.CompareTo(Object value)
// at Example.Main()
//
// Comparing 'some text' with 'TestClass': -1
//
// Bad argument: 123 (type Int32)
// Exception information: System.ArgumentException: Object must be of type String.
// at System.String.CompareTo(Object value)
// at Example.Main()
//
// Comparing 'some text' with '123': 1
//
// Comparing 'some text' with 'some text': 0
//
// Comparing 'some text' with 'Some Text': -1
open System
type TestClass() = class end
let test = TestClass()
let objectsToCompare: obj[] =
[| test; test.ToString(); 123
string 123; "some text"
"Some Text" |]
let s = "some text"
for objectToCompare in objectsToCompare do
try
let i = s.CompareTo objectToCompare
printfn $"Comparing '{s}' with '{objectToCompare}': {i}"
with :? ArgumentException as e ->
printfn $"Bad argument: {objectToCompare} (type {objectToCompare.GetType().Name})"
printfn $"Exception information: {e}"
printfn ""
// The example displays the following output:
// Bad argument: Example+TestClass (type TestClass)
// Exception information: System.ArgumentException: Object must be of type String.
// at System.String.CompareTo(Object value)
// at <StartupCode$fs>.$Example.main@()
//
// Comparing 'some text' with 'Example+TestClass': -1
//
// Bad argument: 123 (type Int32)
// Exception information: System.ArgumentException: Object must be of type String.
// at System.String.CompareTo(Object value)
// at <StartupCode$fs>.$Example.main@()
//
// Comparing 'some text' with '123': 1
//
// Comparing 'some text' with 'some text': 0
//
// Comparing 'some text' with 'Some Text': -1
Public Class TestClass
End Class
Public Class Example
Public Shared Sub Main()
Dim test As New TestClass()
Dim objectsToCompare() As Object = { test, test.ToString(), 123,
123.ToString(), "some text",
"Some Text" }
Dim s As String = "some text"
For Each objectToCompare In objectsToCompare
Try
Dim i As Integer = s.CompareTo(objectToCompare)
Console.WriteLine("Comparing '{0}' with '{1}': {2}",
s, objectToCompare, i)
Catch e As ArgumentException
Console.WriteLine("Bad argument: {0} (type {1})",
objectToCompare,
objectToCompare.GetType().Name)
Console.WriteLine("Exception information: {0}", e)
End Try
Console.WriteLine()
Next
End Sub
End Class
' The example displays the following output:
' Bad argument: TestClass (type TestClass)
' Exception information: System.ArgumentException: Object must be of type String.
' at System.String.CompareTo(Object value)
' at Example.Main()
'
' Comparing 'some text' with 'TestClass': -1
'
' Bad argument: 123 (type Int32)
' Exception information: System.ArgumentException: Object must be of type String.
' at System.String.CompareTo(Object value)
' at Example.Main()
'
' Comparing 'some text' with '123': 1
'
' Comparing 'some text' with 'some text': 0
'
' Comparing 'some text' with 'Some Text': -1
Observações
ToString devolve uma representação da exceção atual que pretende ser compreendida pelos humanos. Quando a exceção contém dados sensíveis à cultura, a representação da cadeia devolvida ToString por deve ter em conta a cultura atual do sistema. Embora não existam requisitos exatos para o formato da cadeia devolvida, esta deve tentar refletir o valor do objeto tal como percebido pelo utilizador.
A implementação padrão de ToString obtém o nome da classe que lançou a exceção atual, a mensagem, o resultado de chamar ToString a exceção interna e o resultado de chamar Environment.StackTrace. Se algum destes elementos for null, o seu valor não é incluído na cadeia devolvida.
Se não houver mensagem de erro ou se for uma cadeia vazia (""), então não é devolvida nenhuma mensagem de erro. O nome da exceção interna e o traço da pilha só são devolvidos se não nullforem .
Este método substitui o Object.ToString.