عبارت throw به شما امکان می دهد یک خطای سفارشی ایجاد کنید.
عبارت throw همراه با کلاس استثنا استفاده می شود. کلاس های استثنای زیادی در C# موجود است: ArithmeticException،FileNotFoundException، ،
IndexOutOfRangeExceptionTimeOutException، و غیره:
static void checkAge(int age)
{
if (age < 18)
{
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else
{
Console.WriteLine("Access granted - You are old enough!");
}
}
static void Main(string[] args)
{
checkAge(15);
}The error message displayed in the program will be:
System.ArithmeticException: 'Access denied - You must be at least 18 years old.'
اگر سن 20 سال بود، نمیافتید استثنا: