Solution: User defined exception
Completion requirements
- using System;
- using System.Runtime.Serialization;
- namespace TaskUserDefException
- {
- [Serializable]
- public class OverflowIntException : Exception
- {
- public OverflowIntException() { }
- public OverflowIntException(string message) : base(message) { }
- public OverflowIntException(string message, Exception inner)
- : base(message, inner) { }
- protected OverflowIntException(SerializationInfo info, StreamingContext context)
- : base(info, context) { }
- }
- class Program
- {
- static void Main(string[] args)
- {
- short i = 0;
- try
- {
- while (true)
- {
- if (i < 0)
- throw new OverflowIntException("Overflow of short integer");
- Console.WriteLine(i++);
- }
- }
- catch(OverflowIntException oie)
- {
- Console.WriteLine(oie.Message);
- Console.ReadKey();
- }
- }
- }
- }
Please note that the above program is not actually necessary. It is only choosen it for didactic reasons.
There is a predefined OverflowException. However, it is only thrown if the keyword checked is used:
- using System;
- namespace TaskUserDefException
- {
- class Program
- {
- static void Main(string[] args)
- {
- short i = 0;
- try
- {
- while (true)
- Console.WriteLine(checked(i++)); // for throwing of exception, 'checked' is nessecary
- }
- catch (OverflowException oe)
- {
- Console.WriteLine(oe.Message);
- Console.ReadKey();
- }
- }
- }
- }
Last modified: Friday, 25 October 2019, 9:23 AM