What is the purpose of throw keyword in C#?

Throw is used to throw exceptions explicitly from your code. It is used for the following purposes:



• To throw pre-defined exceptions from your code
• To throw user-defined exceptions from your code
• To re-throw an exception caught in the catch block to the calling method
Here is an example demonstrating usage of throw keyword to throw user-defined exception:
class sampleException:Exception {
public sampleException(){
Console.WriteLine(“Executing User Defined Exception..”);
}
}
class sampleClass {
public static void Main() {
try {
throw new sampleException();
}
catch(Exception ex) {
Console.WriteLine(“Exception Caught:” + ex.ToString());
}

}
}

Output of this code will be:

Executing User Defined Exception..
Exception Caught: sampleException: Exception of type ‘sampleException’ was thrown at sampleClass.Main()

| What is Private Access Modifier in C#? | What is Protected Access Modifier in C#? | What is Protected Internal Access Modifier in C#? | What is Public Access Modifier in C#? | What is the difference between virtual and abstract keywords in .NET? | What is the importance of Microsoft Application Blocks in .NET Architecture? | What is the need for Factory Method in C# | What is the purpose of ArrayList in .NET? | What is the purpose of Datareader in ADO.NET? | What is the purpose of Dataset in ADO.NET? | What is the purpose of finally block in C#? | What is the purpose of interlocked class in .NET? | What is the purpose of main() function in C# | What is the purpose of ManualResetEvent in .NET? | What is the purpose of sealed method in C#? | What is the purpose of Thread.Join() method in .NET? | What is the purpose of Thread.Sleep() method in .NET? | What is the purpose of throw keyword in C#? | What is the usage of ENUM in .NET? |


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2024 - All Rights Reserved.