declare a method always throws an exception?
I suggest that you convert ThrowSpecificFault(ex)
to throw SpecificFault(ex)
; the SpecificFault
method would return the exception object to be thrown rather than throwing it itself. Much cleaner.
This is the pattern recommended by Microsoft's guidelines (find the text "Use exception builder methods").
Right now a return type can be a type, or "void" meaning "no return type". We could in theory add a second special return type "never", which has the semantics you want. The end point of an expression statement consisting of a call to a "never" returning method would be considered unreachable, and so it would be legal in every context in C# in which a "goto", "throw" or "return" is legal.
It is highly unlikely that this will be added to the type system now, ten years in. Next time you design a type system from scratch, remember to include a "never" type.
The problem here, is that if you go into the catch
block in f()
your function will never return a value. This will result in an error because you declared your function as int
which means you told the compiler that your method will return an integer.
The following code will do what you are looking for and always return an integer.
int f() {
int i = 0;
try {
i = process();
} catch(Exception ex) {
ThrowSpecificFault(ex);
}
return i;
}
put the return statement at the end of your function and you will be fine.
It's always a good idea to ensure your method will always return a value no matter what execution path your application goes through.