werden nach der Empfehlung von Microsoft von der Klasse Exception abgeleitet:

  1. using System;
  2. using System.Runtime.Serialization;
  3.  
  4. namespace UserDefinedException
  5. {
  6.     // benutzerdefinierte Exception (MS VS-Snippet "ex" + TAB)
  7.     [Serializable]
  8.     public class NegativeRadiusException : Exception
  9.     {
  10.         public NegativeRadiusException() { }
  11.         public NegativeRadiusException(string message) : base(message) { }
  12.         public NegativeRadiusException(string message, Exception inner)
  13.             : base(message, inner) { }
  14.         protected NegativeRadiusException(SerializationInfo info, StreamingContext context)
  15.             : base(info, context) { }
  16.     }
  17.     class Program
  18.     {
  19.         static void Main(string[] args)
  20.         {
  21.             try
  22.             {
  23.                 Circle c = new Circle(-1);
  24.             }
  25.             catch (NegativeRadiusException nre)
  26.             {
  27.                 Console.WriteLine(nre.Message);
  28.             }
  29.             Console.ReadKey();
  30.         }
  31.     }
  32.     class Circle
  33.     {
  34.         private double radius;
  35.         public Circle(double r)
  36.         {
  37.             if (r < 0)
  38.                 throw new NegativeRadiusException("Radius darf nicht negativ sein.");
  39.             else
  40.                 radius = r;
  41.         }
  42.         public double A() // Flächenberechnung
  43.         {
  44.             return Math.Pow(radius, 2) * Math.PI;
  45.         }
  46.     }
  47. }





Last modified: Thursday, 29 November 2018, 9:34 AM