Although we have seen the Exceptions provided by C#. But sometimes, we need to create our own Exception.
And luckily, C# provides an Exception, that you can inherit and define your own exception.
Let us see, how we can achieve with the below example.
using System; class MyApplication { public static void Main(string[] args) { int number = 23; try { NumberCheck(number); } catch(Exception e) { Console.WriteLine(e); } } static void NumberCheck(int num) { if (num < 50) { throw new Exception("Number cannot be less than 50"); } else { Console.WriteLine("Number is greater than 50"); } } }
So, we have defined our custom exception that if a number is less than 50. An exception will be raised.
And all we have done is used the throw keyword with the Exception class to raise a custom exception.
throw Exception("Number cannot be less than 50")
So, in the above code we have defined a variable number and initialise it with the number 23.
int number = 23;
Then we have checked, if the value of number is less than 50 or not.
if (number < 50) { throw Exception("Number cannot be less than 50") }
And in this case the value of number is less than 50. So, the exception is triggered, raising the exception using the throw keyword.
throw Exception("Number cannot be less than 50")
And we get the below exception as output.
System.Exception: Number cannot be less than 50