i have a following try catch block
try {
if () {}
else { NOW i wanna go directly to a finally{} block
}
is there a way to do that?
Printable View
i have a following try catch block
try {
if () {}
else { NOW i wanna go directly to a finally{} block
}
is there a way to do that?
Well you can use goto, but its frowned upon.
but how? goto finally
? or what?
I haven't tried it, but try the break statement:
break;
It is useful in loops when you want out, maybe you can break out of a try block...
no, i dont think so because its just for loops and switches
Nevermind, just tried it, it only works for loops.
i cant make goto to a finally block?
After thinking about what your trying to do, I think you are probably approaching the problem wrong. You shouldn't be using error trapping as flow control for your program. You should use it to trap and handle errors. Could you maybe post the whole code your trying to do so I can see if there is a different way for you to go about it.
Jumping to different blocks of code in the same method isn't good practice anyway.
Looking at your example, you can just leave out the else part of the if statement and if the statement isn't true, the finally block will execute:
Code:try
{
if()
{
// your code here
}
}
catch
{
}
finally
{
//Your finally code here.
}
i had the idea of throwing my own exception
No, that's bad.
But your problem is irrelevant IMO. It seems you want to do something like
In that case it should beCode:try {
// stuff
if(expr) {
// stuff
} else {
// stuff
}
// stuff you don't want if it's else
} finally {
// stuff
}
The finally blocks executes even if there is no error.Code:try {
// stuff
if(expr) {
// stuff
// stuff you don't want if it's else
} else {
// stuff
}
} finally {
// stuff
}
Use the return keyword to exit the routine. B/c you are using a finally statement, it will always fire:
Code:private void button1_Click(object sender, System.EventArgs e)
{
bool flag = false;
try
{
if (flag)
{
Console.WriteLine("Do Something..");
}
else
{
return;
}
}
finally
{
MessageBox.Show("Finally Block Executing..");
}
}
always? didnt know of that..iamgine the following example:
this means that it will return false if the value is equal to 5?Code:try {
if (a == 5) {
return true;
else {
MessageBox.show("error");
}
}
finally {
return false;
}
}
You can't use the return keyword in the finally() clause.
hmm interesting fact
But if you were using the Windows SEH in C or C++ then it would always return false, no matter what the value of a is.