I am writing a method which makes sure that the caller is authorized to execute it. When the user isn’t authorized, I have to throw an exception (see code below). What should be the name of that method?
public void Compute() {
this.CheckIfCallerAuthorizedOrThrow(); // Is it a good name? Better idea?
// ...
}
I want to make sure that someone who reads the code understand that the flow of the method can be broken here by an exception. Is that a good or bad practice in this case to have a method name with “throw” in it?
Honestly, a method name should describe exactly what it is supposed to do. So in a way, that’s a good name. However, an exception is a way of saying “This method couldn’t complete successfully and here’s why…”. Just about every method you write could throw an exception, so it wouldn’t make sense to document exceptions in the name of every method.
You should consider using XML documentation. XML documentation is more specific too. It tells what type of exception is being thrown, as well as the specific reasons it will be thrown.
I do actually use method names with “throw” in them, but they are usually really short private methods that I reuse in several other public methods. They usually look like this:
So, in short, that’s potentially a good method name. I just wouldn’t use “throw” in every single method that throws exceptions. Besides, a good developer will need to look at the documentation anyway to see what kind of exceptions are being thrown (I certainly hope he’s not just catching the generic Exception all the time…)