InterviewSolution
Saved Bookmarks
| 1. |
How to create custom exceptions in C#? |
|
Answer» Custom exceptions can be created by users as required by inheriting the exception class. Custom exceptions are usually created if the user needs are not met by any of the predefined exceptions. A custom exception that is thrown if the age provided is negative is given as follows: using System; namespace DEMO { class PROGRAM { static void Main(string[] args) { Age OBJ = new Age(); try { obj.agePrint(); } catch(GivenAgeIsNegativeException E) { Console.WriteLine("GivenAgeIsNegativeException: {0}", e.Message); } } } } public class GivenAgeIsNegativeException: Exception { public GivenAgeIsNegativeException(string message): base(message) { } } public class Age { int age = -20; public void agePrint() { if(age < 0) { throw (new GivenAgeIsNegativeException("ERROR!!! Age cannot be negative")); } else { Console.WriteLine("The age is: {0}", age); } } }The output of the above program is as follows: GivenAgeIsNegativeException: Error!!! Age cannot be negative |
|