2010-01-18 17 views
26

Me preguntaba si hay una lista con todos los tipos de excepciones. Conozco algunas Excepciones, pero no las conozco todas. A veces lanzo una excepción y luego pienso, tal vez .NET ya tiene una excepción para esto.C# ¿Hay una descripción general de excepciones?

Por ejemplo, ahora necesito una excepción que diga que un proceso no existe (como un archivo).

Por lo tanto, mi pregunta es: ¿Alguien sabe para encontrar una lista de todas las excepciones? No lo encontré

Respuesta

20

En primer lugar hay que entender cuáles son excepciones y cómo tratar con él. Hay algunos recursos que pueden ayudarlo a comprender este tema.

  1. "Elegir el tipo correcto de excepción para lanzar" por Krzysztof Cwalina.http://blogs.msdn.com/kcwalina/archive/2006/07/05/657268.aspx

  2. "Cómo diseñar excepciones de jerarquía" de Krzysztof Cwalina. http://blogs.msdn.com/kcwalina/archive/2007/01/30/ExceptionHierarchies.aspx

  3. El modo de excepción de Chris Brumme. http://blogs.msdn.com/cbrumme/archive/2003/10/01/51524.aspx

pueden ser útiles:

  1. "¿Por catch (Exception)/vacío captura es malo" por el blog del equipo de CLR. http://blogs.msdn.com/b/dotnet/archive/2009/02/19/why-catch-exception-empty-catch-is-bad.aspx

  2. "Write Robust Exception-Handling Code" de Bill Wagner. http://visualstudiomagazine.com/articles/2007/06/01/write-robust-exceptionhandling-code.aspx

  3. "C#: ¿Necesitamos excepción comprobada en C#" https://blogs.msdn.com/abhinaba/archive/2005/12/16/504373.aspx

También Jeffrey Richter en su CLR libro a través de C# jerarquía de acumulación excepción (p.430, Capítulo 19) y últimamente escribió una programa que mostrará todas las clases que se derivan en última instancia de System.Exception:

using System; 
using System.Text; 
using System.Reflection; 
using System.Collections.Generic; 
public static class Program 
{ 
    public static void Main() 
    { 
     // Explicitly load the assemblies that we want to reflect over 
     LoadAssemblies(); 
     // Initialize our counters and our exception type list 
     Int32 totalPublicTypes = 0, totalExceptionTypes = 0; 
     List<String> exceptionTree = new List<String>(); 
     // Iterate through all assemblies loaded in this AppDomain 
     foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) 
     { 
      // Iterate through all types defined in this assembly 
      foreach (Type t in a.GetExportedTypes()) 
      { 
       totalPublicTypes++; 
       // Ignore type if not a public class 
       if (!t.IsClass || !t.IsPublic) continue; 
       // Build a string of the type's derivation hierarchy 
       StringBuilder typeHierarchy = new StringBuilder(t.FullName, 5000); 
       // Assume that the type is not an Exception-derived type 
       Boolean derivedFromException = false; 
       // See if System.Exception is a base type of this type 
       Type baseType = t.BaseType; 
       while ((baseType != null) && !derivedFromException) 
       { 
        // Append the base type to the end of the string 
        typeHierarchy.Append("-" + baseType); 
        derivedFromException = (baseType == typeof(System.Exception)); 
        baseType = baseType.BaseType; 
       } 
       // No more bases and not Exception-derived, try next type 
       if (!derivedFromException) continue; 
       // We found an Exception-derived type 
       totalExceptionTypes++; 
       // For this Exception-derived type, 
       // reverse the order of the types in the hierarchy 
       String[] h = typeHierarchy.ToString().Split('-'); 
       Array.Reverse(h); 
       // Build a new string with the hierarchy in order 
       // from Exception -> Exception-derived type 
       // Add the string to the list of Exception types 
       exceptionTree.Add(String.Join("-", h, 1, h.Length - 1)); 
      } 
     } 
     // Sort the Exception types together in order of their hierarchy 
     exceptionTree.Sort(); 
     // Display the Exception tree 
     foreach (String s in exceptionTree) 
     { 
      // For this Exception type, split its base types apart 
      string[] x = s.Split('-'); 
      // Indent based on the number of base types 
      // and then show the most-derived type 
      Console.WriteLine(new String(' ', 3 * x.Length) + x[x.Length - 1]); 
     } 
     // Show final status of the types considered 
     Console.WriteLine("\n---> of {0} types, {1} are " + 
     "derived from System.Exception.", 
     totalPublicTypes, totalExceptionTypes); 
    } 
    private static void LoadAssemblies() 
    { 
     String[] assemblies = { 
       "System, PublicKeyToken={0}", 
       "System.Data, PublicKeyToken={0}", 
       "System.Design, PublicKeyToken={1}", 
       "System.DirectoryServices, PublicKeyToken={1}", 
       "System.Drawing, PublicKeyToken={1}", 
       "System.Drawing.Design, PublicKeyToken={1}", 
       "System.Management, PublicKeyToken={1}", 
       "System.Messaging, PublicKeyToken={1}", 
       "System.Runtime.Remoting, PublicKeyToken={0}", 
       "System.Security, PublicKeyToken={1}", 
       "System.ServiceProcess, PublicKeyToken={1}", 
       "System.Web, PublicKeyToken={1}", 
       "System.Web.RegularExpressions, PublicKeyToken={1}", 
       "System.Web.Services, PublicKeyToken={1}", 
       "System.Windows.Forms, PublicKeyToken={0}", 
       "System.Xml, PublicKeyToken={0}", 
       }; 
     String EcmaPublicKeyToken = "b77a5c561934e089"; 
     String MSPublicKeyToken = "b03f5f7f11d50a3a"; 
     // Get the version of the assembly containing System.Object 
     // We'll assume the same version for all the other assemblies 
     Version version = 
     typeof(System.Object).Assembly.GetName().Version; 
     // Explicitly load the assemblies that we want to reflect over 
     foreach (String a in assemblies) 
     { 
      String Assemblyldentity = 
      String.Format(a, EcmaPublicKeyToken, MSPublicKeyToken) + 
      ", Culture=neutral, Version=" + version; 
      Assembly.Load(AssemblyIdentity); 
     } 
    } 
} 
+0

La lista 1 en "Puede ser útil" ha sido eliminada. Esta es una versión en vivo: http://blogs.msdn.com/b/dotnet/archive/2009/02/19/why-catch-exception-empty-catch-is-bad.aspx –

+0

@La publicación de Matt ha sido editada con el enlace que proporcionaste ¡Buena atrapada! –

8

Hay un Exception Hierarchy.

Además, MSDN tiene una jerarquía de herencia en la página para el Exception class. Pero esa es solo una larga lista y no proporciona muchos detalles.

En general, parece que .NET tiene muy pocas excepciones integradas generales.

2

Puede encontrar todas las excepciones definidas bajo los tipos derivados de System.Exception en el MSDN page para System.Exception (encuéntrelo en la sección Jerarquía de herencia).

6

Una buena forma de ver todos los tipos que se derivan de System.Exception en el marco .NET es usando Reflector.

  1. Tipo F3 para buscar 'System.Exception'
  2. Seleccione la 'System.Exception' Tipo
  3. Ampliar el 'tipos derivados' nodo del árbol.

Tenga en cuenta que Reflector le permite agregar dinamicamente cualquier ensamblado .NET, lo que significa que buscará los tipos derivados de System.Exception en cualquier conjunto personalizado de ensamblados que proporcione. Los ensamblados de .NET Framework más comunes se agregan de forma predeterminada.

Cuestiones relacionadas