wird im catch-Block erneut eine weitere Exception geworfen, so schlägt das Exception handling fehl und die ursprüngliche Exception muss erneut geworfen werden. Dabei wird die neue Exception als Parameter „inner exception“ übergeben. Im Beispiel werden in Main() alle aufgetretenen Exceptions mit beliebiger Verschachtelungstiefe ausgegeben.

  1. using System;
  2. using System.IO;
  3.  
  4. class Test
  5. {
  6.     public static void Main()
  7.     {
  8.         try
  9.         {
  10.             Division div = new Division();
  11.         }
  12.         catch(Exception e)
  13.         {    // alle Exceptions mit beliebiger Verschachtelungstiefe ausgeben
  14.             Exception currentEx = e;
  15.             while (currentEx != null)
  16.             {
  17.                 Console.WriteLine(currentEx.Message);
  18.                 currentEx = currentEx.InnerException;
  19.             }
  20.         }
  21.         Console.ReadKey();
  22.     }
  23. }
  24. class Division
  25. {
  26.     static int zero = 0;
  27.     public Division()
  28.     {
  29.         try
  30.         {
  31.             int j = 1 / zero;
  32.         }
  33.         catch (DivideByZeroException dbze)
  34.         {
  35.             StreamWriter sw = null;
  36.             try
  37.             {   // Exception handling schlägt fehl (* im Dateinamen)!
  38.                 sw = new StreamWriter("ungültig*txt");
  39.                 sw.Write(dbze);
  40.             }
  41.             catch (Exception e)
  42.             {   // Exception erneut werfen mit Parameter innerException
  43.                 throw new DivideByZeroException(dbze.Message, e);
  44.             }
  45.             finally
  46.             {
  47.                 if (sw != null)
  48.                     sw.Close();
  49.             }
  50.         }
  51.     }
  52. }

https://msdn.microsoft.com/de-de/library/system.exception.getbaseexception%28v=vs.110%29.aspx (20.07.2015)

Last modified: Wednesday, 1 December 2021, 1:04 PM