Benutzerdefinierte Exceptions
Completion requirements
werden nach der Empfehlung von Microsoft von der Klasse Exception abgeleitet:
- using System;
- using System.Runtime.Serialization;
- namespace UserDefinedException
- {
- // benutzerdefinierte Exception (MS VS-Snippet "ex" + TAB)
- [Serializable]
- public class NegativeRadiusException : Exception
- {
- public NegativeRadiusException() { }
- public NegativeRadiusException(string message) : base(message) { }
- public NegativeRadiusException(string message, Exception inner)
- : base(message, inner) { }
- protected NegativeRadiusException(SerializationInfo info, StreamingContext context)
- : base(info, context) { }
- }
- class Program
- {
- static void Main(string[] args)
- {
- try
- {
- Circle c = new Circle(-1);
- }
- catch (NegativeRadiusException nre)
- {
- Console.WriteLine(nre.Message);
- }
- Console.ReadKey();
- }
- }
- class Circle
- {
- private double radius;
- public Circle(double r)
- {
- if (r < 0)
- throw new NegativeRadiusException("Radius darf nicht negativ sein.");
- else
- radius = r;
- }
- public double A() // Flächenberechnung
- {
- return Math.Pow(radius, 2) * Math.PI;
- }
- }
- }
Last modified: Thursday, 29 November 2018, 9:34 AM