Verschachtelte Exceptions
Completion requirements
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.
- using System;
- using System.IO;
- class Test
- {
- public static void Main()
- {
- try
- {
- Division div = new Division();
- }
- catch(Exception e)
- { // alle Exceptions mit beliebiger Verschachtelungstiefe ausgeben
- Exception currentEx = e;
- while (currentEx != null)
- {
- Console.WriteLine(currentEx.Message);
- currentEx = currentEx.InnerException;
- }
- }
- Console.ReadKey();
- }
- }
- class Division
- {
- static int zero = 0;
- public Division()
- {
- try
- {
- int j = 1 / zero;
- }
- catch (DivideByZeroException dbze)
- {
- StreamWriter sw = null;
- try
- { // Exception handling schlägt fehl (* im Dateinamen)!
- sw = new StreamWriter("ungültig*txt");
- sw.Write(dbze);
- }
- catch (Exception e)
- { // Exception erneut werfen mit Parameter innerException
- throw new DivideByZeroException(dbze.Message, e);
- }
- finally
- {
- if (sw != null)
- sw.Close();
- }
- }
- }
- }
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