The Best practices for exceptions document on MSDN says that you can have an exception builder method inside your class if the same exception is to be used in many parts of the class. But also, it says that in some cases, it's better to use the exception's constructor.
Let's say I have the following code in an UserData
class:
private MailAddress _addr;
public UserData(string emailAddress)
{
// Tries to validate the e-mail address
try
{
_addr = new MailAddress(emailAddress);
}
catch
{
throw new ArgumentException(nameof(emailAddress), "Invalid email address.");
}
if (_addr.Address != emailAddress)
{
throw new ArgumentException(nameof(emailAddress), "Invalid email address.");
}
}
You can see that in both throw
statements, I'm throwing the exact same exception.
The question is: Is it correct to add an exception builder method to get my exception and throw that? Will I get the correct stacktrace and such if I do so? And if not, how do I determine between exception builders and constructors?
Is it correct to add an exception builder method to get my exception and throw that
That depends. As suggested in the article you linked: If it's the same exception (with the same information), it makes sense to create such a helper method to keep your code clean.
Will I get the correct stacktrace and such if I do so
Yes, you will. Take a look at this example. (DotNetFiddle).
public static void Main()
{
try{
throw CreateEx("Hi");
} catch(Exception ex) {
Console.WriteLine(ex.ToString());
}
try {
CreateEx2("Hi");
} catch(Exception ex) {
Console.WriteLine(ex.ToString());
}
}
public static Exception CreateEx(string text){
text += " Additional text";
return new ArgumentOutOfRangeException(text);
}
public static void CreateEx2(string text){
text += " Additional text";
throw new ArgumentOutOfRangeException(text);
}
The stacktrace depends on where the exception is thrown, not where it is built.
System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: Hi Additional text
at Program.Main() in d:\Windows\Temp\b4ln3dbq.0.cs:line 13
System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: Hi Additional text
at Program.CreateEx2(String text) in d:\Windows\Temp\b4ln3dbq.0.cs:line 34
at Program.Main() in d:\Windows\Temp\b4ln3dbq.0.cs:line 19
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With