I want to catch the exception threw at different steps. Look at the code below. Let us say each function Procedure1, Procedure2,... ,Procedure6 may throw various kinds of exceptions (may overlap!). And if exception happened at step 1-3, I want to throw newly-defined exception ex1 and step 4-6 ex2.
public void TestFunc(){
try{
var res1 = Procedure1();
var res2 = Procedure2(res1);
var res3 = Procedure3(res2);
var res4 = Procedure4(res3);
var res5 = Procedure5(res4);
Procedure6(res5);
}
catch{
// if error/exception occurs in step 1-3 throw exception 1
}
catch{
// if error/exception occurs in step 4-6 throw exception 2
}
}
I have read https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-catch but really did not get the point.
If all steps throw different exceptions, then I can catch different ones. But the exceptions for different steps may overlap. So I cannot really tell which step it is from the exception message. (Yeah, this is can be overcome by adding extra info on exception messages, but again I really do not want to modify other functions.)
One way I can think of is to break the TestFunc into two piece, but again I really do not want to do this as it breaks the integrity of the function.
And if we break the steps into two try, the editor shows the message res3 does not exist in the context. This is reasonable as {} separates the context.
public void TestFunc(){
try{
var res1 = Procedure1();
var res2 = Procedure2(res1);
var res3 = Procedure3(res2);
}
catch{
// if error in step 1-3 throw exception 1
}
try{
var res4 = Procedure4(res3); // error, res3 cannot be found in the context
var res5 = Procedure5(res4);
Procedure6(res5);
}
catch{
// if error in step 4-6 throw exception 2
}
}