|
web
newsgroups
|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
Try Catch Else FinallyAnother wish of mine. I wish there was a way in the Try Catch structure
to say if there wasn't an error to do something. Like an else statement. Try Catch Else Finally. Also because I understand Finally runs whether an error was caught or not, I haven't found a use for finally yet. That's what the Try is for. To do stuff with the assumption that there are
no errors. The catch is to deal with any errors. And the finally is to run regardless of whether or not there were errors. Show quoteHide quote "cj" <cj@nospam.nospam> wrote in message news:uOwfvRdSGHA.5552@TK2MSFTNGP14.phx.gbl... > Another wish of mine. I wish there was a way in the Try Catch structure > to say if there wasn't an error to do something. Like an else statement. > Try Catch Else Finally. > > Also because I understand Finally runs whether an error was caught or not, > I haven't found a use for finally yet. > So are you saying if I have that if line 2 throws and exception it will
skip 3, 4 and 5 and go straight to catch? If so, the next question is how do I know it was line 2 that threw the exception and not line 1 or 4? try 1 2 3 4 5 catch a end try Marina Levit [MVP] wrote: Show quoteHide quote > That's what the Try is for. To do stuff with the assumption that there are > no errors. The catch is to deal with any errors. And the finally is to run > regardless of whether or not there were errors. > > "cj" <cj@nospam.nospam> wrote in message > news:uOwfvRdSGHA.5552@TK2MSFTNGP14.phx.gbl... >> Another wish of mine. I wish there was a way in the Try Catch structure >> to say if there wasn't an error to do something. Like an else statement. >> Try Catch Else Finally. >> >> Also because I understand Finally runs whether an error was caught or not, >> I haven't found a use for finally yet. >> > > Yes, that is what I am saying. That is the whole point of a try block.
You wouldn't know which one it was. You would need a separate try/catch for each line of code if you had different error handling code depending on which exact one threw the exception. Or if the different things threw different types of exceptions, you could have multiple catch blocks each catching a different exception type, and have different error handling code execute that way. Show quoteHide quote "cj" <cj@nospam.nospam> wrote in message news:%23rn7ZedSGHA.4740@TK2MSFTNGP14.phx.gbl... > So are you saying if I have that if line 2 throws and exception it will > skip 3, 4 and 5 and go straight to catch? > > If so, the next question is how do I know it was line 2 that threw the > exception and not line 1 or 4? > > try > 1 > 2 > 3 > 4 > 5 > catch > a > end try > > Marina Levit [MVP] wrote: >> That's what the Try is for. To do stuff with the assumption that there >> are no errors. The catch is to deal with any errors. And the finally is >> to run regardless of whether or not there were errors. >> >> "cj" <cj@nospam.nospam> wrote in message >> news:uOwfvRdSGHA.5552@TK2MSFTNGP14.phx.gbl... >>> Another wish of mine. I wish there was a way in the Try Catch structure >>> to say if there wasn't an error to do something. Like an else >>> statement. Try Catch Else Finally. >>> >>> Also because I understand Finally runs whether an error was caught or >>> not, I haven't found a use for finally yet. >>> >> Thanks, I really didn't know or at least think about doing it that way.
I knew several lines could be in try but I guess I was still thinking I needed to check soon to see if a particular line had an exception. I guess I still do but I guess I can have nested try blocks. That'd probably take care of my issues. Thanks! Marina Levit [MVP] wrote: Show quoteHide quote > Yes, that is what I am saying. That is the whole point of a try block. > > You wouldn't know which one it was. You would need a separate try/catch for > each line of code if you had different error handling code depending on > which exact one threw the exception. > Or if the different things threw different types of exceptions, you could > have multiple catch blocks each catching a different exception type, and > have different error handling code execute that way. > > "cj" <cj@nospam.nospam> wrote in message > news:%23rn7ZedSGHA.4740@TK2MSFTNGP14.phx.gbl... >> So are you saying if I have that if line 2 throws and exception it will >> skip 3, 4 and 5 and go straight to catch? >> >> If so, the next question is how do I know it was line 2 that threw the >> exception and not line 1 or 4? >> >> try >> 1 >> 2 >> 3 >> 4 >> 5 >> catch >> a >> end try >> >> Marina Levit [MVP] wrote: >>> That's what the Try is for. To do stuff with the assumption that there >>> are no errors. The catch is to deal with any errors. And the finally is >>> to run regardless of whether or not there were errors. >>> >>> "cj" <cj@nospam.nospam> wrote in message >>> news:uOwfvRdSGHA.5552@TK2MSFTNGP14.phx.gbl... >>>> Another wish of mine. I wish there was a way in the Try Catch structure >>>> to say if there wasn't an error to do something. Like an else >>>> statement. Try Catch Else Finally. >>>> >>>> Also because I understand Finally runs whether an error was caught or >>>> not, I haven't found a use for finally yet. >>>> > If I call a sub as one of the inside within a try, would the try trap
errors in the sub? I hope not. My intention is only that this sub should only be run if there were no errors in the statement before it. Also I'm not sure I understand Finally. How are statements in finally different from those that follow the end try? Marina Levit [MVP] wrote: Show quoteHide quote > Yes, that is what I am saying. That is the whole point of a try block. > > You wouldn't know which one it was. You would need a separate try/catch for > each line of code if you had different error handling code depending on > which exact one threw the exception. > Or if the different things threw different types of exceptions, you could > have multiple catch blocks each catching a different exception type, and > have different error handling code execute that way. > > "cj" <cj@nospam.nospam> wrote in message > news:%23rn7ZedSGHA.4740@TK2MSFTNGP14.phx.gbl... >> So are you saying if I have that if line 2 throws and exception it will >> skip 3, 4 and 5 and go straight to catch? >> >> If so, the next question is how do I know it was line 2 that threw the >> exception and not line 1 or 4? >> >> try >> 1 >> 2 >> 3 >> 4 >> 5 >> catch >> a >> end try >> >> Marina Levit [MVP] wrote: >>> That's what the Try is for. To do stuff with the assumption that there >>> are no errors. The catch is to deal with any errors. And the finally is >>> to run regardless of whether or not there were errors. >>> >>> "cj" <cj@nospam.nospam> wrote in message >>> news:uOwfvRdSGHA.5552@TK2MSFTNGP14.phx.gbl... >>>> Another wish of mine. I wish there was a way in the Try Catch structure >>>> to say if there wasn't an error to do something. Like an else >>>> statement. Try Catch Else Finally. >>>> >>>> Also because I understand Finally runs whether an error was caught or >>>> not, I haven't found a use for finally yet. >>>> > I don't really follow what you are saying here.
I would re-evaluate if you really need different error handling logic for every statement. Nested try/catch blocks look pretty ugly and are hard to follow. The finally statements are different because they execute after the Try if no errors happened. They also execute if there was an error and a catch was run. The Finally block is guaranteed to execute regardless of whether or not an error occurred in the Try. I recommend you read up on try/catch/finally blocks in the documentation and take a look at some samples. That might help you figure out the right way of using it. Show quoteHide quote "cj" <cj@nospam.nospam> wrote in message news:O%23fbnudSGHA.4300@TK2MSFTNGP14.phx.gbl... > If I call a sub as one of the inside within a try, would the try trap > errors in the sub? I hope not. My intention is only that this sub should > only be run if there were no errors in the statement before it. > > Also I'm not sure I understand Finally. How are statements in finally > different from those that follow the end try? > > > Marina Levit [MVP] wrote: >> Yes, that is what I am saying. That is the whole point of a try block. >> >> You wouldn't know which one it was. You would need a separate try/catch >> for each line of code if you had different error handling code depending >> on which exact one threw the exception. >> Or if the different things threw different types of exceptions, you could >> have multiple catch blocks each catching a different exception type, and >> have different error handling code execute that way. >> >> "cj" <cj@nospam.nospam> wrote in message >> news:%23rn7ZedSGHA.4740@TK2MSFTNGP14.phx.gbl... >>> So are you saying if I have that if line 2 throws and exception it will >>> skip 3, 4 and 5 and go straight to catch? >>> >>> If so, the next question is how do I know it was line 2 that threw the >>> exception and not line 1 or 4? >>> >>> try >>> 1 >>> 2 >>> 3 >>> 4 >>> 5 >>> catch >>> a >>> end try >>> >>> Marina Levit [MVP] wrote: >>>> That's what the Try is for. To do stuff with the assumption that there >>>> are no errors. The catch is to deal with any errors. And the finally is >>>> to run regardless of whether or not there were errors. >>>> >>>> "cj" <cj@nospam.nospam> wrote in message >>>> news:uOwfvRdSGHA.5552@TK2MSFTNGP14.phx.gbl... >>>>> Another wish of mine. I wish there was a way in the Try Catch >>>>> structure to say if there wasn't an error to do something. Like an >>>>> else statement. Try Catch Else Finally. >>>>> >>>>> Also because I understand Finally runs whether an error was caught or >>>>> not, I haven't found a use for finally yet. >>>>> >> My cut and paste typing was pretty bad wasn't it. Let me try again.
I have this now. The IF that checks to see if I got back session dropped should not execute if respstr=proxy.validate failed. Here I ensure that by checking to see if respstr="" Try respstr = proxy.validate(soapmesg) Catch ex As Exception procLabel2.Text = Now() & " Error executing Validation request" procLabel3.Text = ex.Message respstr = "" End Try If Not respstr = "" And respstr.Substring(0, 28) = _ "Session Dropped, Login Again" Then loginABC(Me, Nothing) End If Suppose I did this instead: Try respstr = proxy.validate(soapmesg) If respstr.Substring(0, 28) = "Session Dropped, Login Again" Then loginABC(Me, Nothing) End If Catch ex As Exception procLabel2.Text = Now() & " Error executing Validation request" procLabel3.Text = ex.Message End Try Is it possible the catch would catch and error that occured in loginABC? I hope not. Marina Levit [MVP] wrote: Show quoteHide quote > I don't really follow what you are saying here. > > I would re-evaluate if you really need different error handling logic for > every statement. Nested try/catch blocks look pretty ugly and are hard to > follow. > > The finally statements are different because they execute after the Try if > no errors happened. They also execute if there was an error and a catch was > run. The Finally block is guaranteed to execute regardless of whether or not > an error occurred in the Try. > > I recommend you read up on try/catch/finally blocks in the documentation and > take a look at some samples. That might help you figure out the right way of > using it. > > "cj" <cj@nospam.nospam> wrote in message > news:O%23fbnudSGHA.4300@TK2MSFTNGP14.phx.gbl... >> If I call a sub as one of the inside within a try, would the try trap >> errors in the sub? I hope not. My intention is only that this sub should >> only be run if there were no errors in the statement before it. >> >> Also I'm not sure I understand Finally. How are statements in finally >> different from those that follow the end try? >> >> >> Marina Levit [MVP] wrote: >>> Yes, that is what I am saying. That is the whole point of a try block. >>> >>> You wouldn't know which one it was. You would need a separate try/catch >>> for each line of code if you had different error handling code depending >>> on which exact one threw the exception. >>> Or if the different things threw different types of exceptions, you could >>> have multiple catch blocks each catching a different exception type, and >>> have different error handling code execute that way. >>> >>> "cj" <cj@nospam.nospam> wrote in message >>> news:%23rn7ZedSGHA.4740@TK2MSFTNGP14.phx.gbl... >>>> So are you saying if I have that if line 2 throws and exception it will >>>> skip 3, 4 and 5 and go straight to catch? >>>> >>>> If so, the next question is how do I know it was line 2 that threw the >>>> exception and not line 1 or 4? >>>> >>>> try >>>> 1 >>>> 2 >>>> 3 >>>> 4 >>>> 5 >>>> catch >>>> a >>>> end try >>>> >>>> Marina Levit [MVP] wrote: >>>>> That's what the Try is for. To do stuff with the assumption that there >>>>> are no errors. The catch is to deal with any errors. And the finally is >>>>> to run regardless of whether or not there were errors. >>>>> >>>>> "cj" <cj@nospam.nospam> wrote in message >>>>> news:uOwfvRdSGHA.5552@TK2MSFTNGP14.phx.gbl... >>>>>> Another wish of mine. I wish there was a way in the Try Catch >>>>>> structure to say if there wasn't an error to do something. Like an >>>>>> else statement. Try Catch Else Finally. >>>>>> >>>>>> Also because I understand Finally runs whether an error was caught or >>>>>> not, I haven't found a use for finally yet. >>>>>> > > CJ,
The statements in the finally block will be always executed unless you power your computer down before that or execute the End statement. (Even if there is a return in the sub than the finally will be done first). I hope this helps, Cor Show quoteHide quote "cj" <cj@nospam.nospam> schreef in bericht news:O%23fbnudSGHA.4300@TK2MSFTNGP14.phx.gbl... > If I call a sub as one of the inside within a try, would the try trap > errors in the sub? I hope not. My intention is only that this sub should > only be run if there were no errors in the statement before it. > > Also I'm not sure I understand Finally. How are statements in finally > different from those that follow the end try? > > > Marina Levit [MVP] wrote: >> Yes, that is what I am saying. That is the whole point of a try block. >> >> You wouldn't know which one it was. You would need a separate try/catch >> for each line of code if you had different error handling code depending >> on which exact one threw the exception. >> Or if the different things threw different types of exceptions, you could >> have multiple catch blocks each catching a different exception type, and >> have different error handling code execute that way. >> >> "cj" <cj@nospam.nospam> wrote in message >> news:%23rn7ZedSGHA.4740@TK2MSFTNGP14.phx.gbl... >>> So are you saying if I have that if line 2 throws and exception it will >>> skip 3, 4 and 5 and go straight to catch? >>> >>> If so, the next question is how do I know it was line 2 that threw the >>> exception and not line 1 or 4? >>> >>> try >>> 1 >>> 2 >>> 3 >>> 4 >>> 5 >>> catch >>> a >>> end try >>> >>> Marina Levit [MVP] wrote: >>>> That's what the Try is for. To do stuff with the assumption that there >>>> are no errors. The catch is to deal with any errors. And the finally is >>>> to run regardless of whether or not there were errors. >>>> >>>> "cj" <cj@nospam.nospam> wrote in message >>>> news:uOwfvRdSGHA.5552@TK2MSFTNGP14.phx.gbl... >>>>> Another wish of mine. I wish there was a way in the Try Catch >>>>> structure to say if there wasn't an error to do something. Like an >>>>> else statement. Try Catch Else Finally. >>>>> >>>>> Also because I understand Finally runs whether an error was caught or >>>>> not, I haven't found a use for finally yet. >>>>> >> I guess I'll have to do some reading on finally. I'm still not sure I
see the use. Perhaps it's how I'm using try catch. My purpose in using try catch is that without it, or some other error handling, if a command throws an exception the program halts with some garbage on the screen. I've written my program with try catch around statements like calls to other servers where something like a cable being cut might cause the line to throw and exception as it can not execute. In the catch I want to know what command is giving the problem. That'll help me know what is wrong. I print a custom message to indicate what code is being executed and the ex.message info to the screen for diagnosis. I need to know which stored procedure will not work, or is it the request to the remote server or did it try to parse the xml file and find out it wasn't a xml file? The presence of an error like this can mean skip the current record or it might mean reattempt the failed command until it starts working. In any event after the try catch the program continues to run. I test a flag variable or some other way to see if the previous statement threw an exception and make my processing decisions based on that. So my code after the try catch always executes--how is that different from being in finally? Cor Ligthert [MVP] wrote: Show quoteHide quote > CJ, > > The statements in the finally block will be always executed unless you power > your computer down before that or execute the End statement. (Even if there > is a return in the sub than the finally will be done first). > > I hope this helps, > > Cor > > "cj" <cj@nospam.nospam> schreef in bericht > news:O%23fbnudSGHA.4300@TK2MSFTNGP14.phx.gbl... >> If I call a sub as one of the inside within a try, would the try trap >> errors in the sub? I hope not. My intention is only that this sub should >> only be run if there were no errors in the statement before it. >> >> Also I'm not sure I understand Finally. How are statements in finally >> different from those that follow the end try? >> >> >> Marina Levit [MVP] wrote: >>> Yes, that is what I am saying. That is the whole point of a try block. >>> >>> You wouldn't know which one it was. You would need a separate try/catch >>> for each line of code if you had different error handling code depending >>> on which exact one threw the exception. >>> Or if the different things threw different types of exceptions, you could >>> have multiple catch blocks each catching a different exception type, and >>> have different error handling code execute that way. >>> >>> "cj" <cj@nospam.nospam> wrote in message >>> news:%23rn7ZedSGHA.4740@TK2MSFTNGP14.phx.gbl... >>>> So are you saying if I have that if line 2 throws and exception it will >>>> skip 3, 4 and 5 and go straight to catch? >>>> >>>> If so, the next question is how do I know it was line 2 that threw the >>>> exception and not line 1 or 4? >>>> >>>> try >>>> 1 >>>> 2 >>>> 3 >>>> 4 >>>> 5 >>>> catch >>>> a >>>> end try >>>> >>>> Marina Levit [MVP] wrote: >>>>> That's what the Try is for. To do stuff with the assumption that there >>>>> are no errors. The catch is to deal with any errors. And the finally is >>>>> to run regardless of whether or not there were errors. >>>>> >>>>> "cj" <cj@nospam.nospam> wrote in message >>>>> news:uOwfvRdSGHA.5552@TK2MSFTNGP14.phx.gbl... >>>>>> Another wish of mine. I wish there was a way in the Try Catch >>>>>> structure to say if there wasn't an error to do something. Like an >>>>>> else statement. Try Catch Else Finally. >>>>>> >>>>>> Also because I understand Finally runs whether an error was caught or >>>>>> not, I haven't found a use for finally yet. >>>>>> > > Hi CJ
Here is an example <code> Sub Button1_Click(...) Handles ... Try DoFileStuff Catch ex As Exception ' This is a catch-all because we don't want ' our button click handler to blow up MessageBox.Show(ex.Message) End Try End Sub Sub DoFileStuff() Try OpenFile WriteToFile Catch ex As SpecificException ' Catch this exception because we know what to do if it occurs Catch ex As SomeOtherExceptionThatICanHandle ' Catch this exception as well for the same reason. However ' it requires a different reaction, so we catch it separately Finally ' This will always execute, even if UnexpectedException is thrown If FileIsOpen Then CloseFile End If End Try ' Code here will not execute if UnexpectedException is thrown, ' so we cannot rely on closing the file here End Sub </code> HTH Charles Show quoteHide quote "cj" <cj@nospam.nospam> wrote in message news:%2384myMeSGHA.6084@TK2MSFTNGP14.phx.gbl... >I guess I'll have to do some reading on finally. I'm still not sure I see >the use. Perhaps it's how I'm using try catch. My purpose in using try >catch is that without it, or some other error handling, if a command throws >an exception the program halts with some garbage on the screen. I've >written my program with try catch around statements like calls to other >servers where something like a cable being cut might cause the line to >throw and exception as it can not execute. In the catch I want to know >what command is giving the problem. That'll help me know what is wrong. I >print a custom message to indicate what code is being executed and the >ex.message info to the screen for diagnosis. I need to know which stored >procedure will not work, or is it the request to the remote server or did >it try to parse the xml file and find out it wasn't a xml file? The >presence of an error like this can mean skip the current record or it might >mean reattempt the failed command until it starts working. > > In any event after the try catch the program continues to run. I test a > flag variable or some other way to see if the previous statement threw an > exception and make my processing decisions based on that. So my code > after the try catch always executes--how is that different from being in > finally? > > Cor Ligthert [MVP] wrote: >> CJ, >> >> The statements in the finally block will be always executed unless you >> power your computer down before that or execute the End statement. (Even >> if there is a return in the sub than the finally will be done first). >> >> I hope this helps, >> >> Cor >> >> "cj" <cj@nospam.nospam> schreef in bericht >> news:O%23fbnudSGHA.4300@TK2MSFTNGP14.phx.gbl... >>> If I call a sub as one of the inside within a try, would the try trap >>> errors in the sub? I hope not. My intention is only that this sub >>> should only be run if there were no errors in the statement before it. >>> >>> Also I'm not sure I understand Finally. How are statements in finally >>> different from those that follow the end try? >>> >>> >>> Marina Levit [MVP] wrote: >>>> Yes, that is what I am saying. That is the whole point of a try block. >>>> >>>> You wouldn't know which one it was. You would need a separate >>>> try/catch for each line of code if you had different error handling >>>> code depending on which exact one threw the exception. >>>> Or if the different things threw different types of exceptions, you >>>> could have multiple catch blocks each catching a different exception >>>> type, and have different error handling code execute that way. >>>> >>>> "cj" <cj@nospam.nospam> wrote in message >>>> news:%23rn7ZedSGHA.4740@TK2MSFTNGP14.phx.gbl... >>>>> So are you saying if I have that if line 2 throws and exception it >>>>> will skip 3, 4 and 5 and go straight to catch? >>>>> >>>>> If so, the next question is how do I know it was line 2 that threw the >>>>> exception and not line 1 or 4? >>>>> >>>>> try >>>>> 1 >>>>> 2 >>>>> 3 >>>>> 4 >>>>> 5 >>>>> catch >>>>> a >>>>> end try >>>>> >>>>> Marina Levit [MVP] wrote: >>>>>> That's what the Try is for. To do stuff with the assumption that >>>>>> there are no errors. The catch is to deal with any errors. And the >>>>>> finally is to run regardless of whether or not there were errors. >>>>>> >>>>>> "cj" <cj@nospam.nospam> wrote in message >>>>>> news:uOwfvRdSGHA.5552@TK2MSFTNGP14.phx.gbl... >>>>>>> Another wish of mine. I wish there was a way in the Try Catch >>>>>>> structure to say if there wasn't an error to do something. Like an >>>>>>> else statement. Try Catch Else Finally. >>>>>>> >>>>>>> Also because I understand Finally runs whether an error was caught >>>>>>> or not, I haven't found a use for finally yet. >>>>>>> >> I see a couple things here.
1. is the button1_click catch catching exceptions thrown by lines inside dofilestuff or just if the line dofilestuff itself for some reason threw an exception? 2. your catching different types of exceptions. I'm catching any exceptions and treating them all the same. The show must go on in my program regardless of any exceptions. Some lines an exception on them would be best handled by retrying the line and others by skipping to the next iteration of the program. ie on reading from a server it'd be best to retry untill it works while on getting a badly formated xml file from the server I'd probably flag that transaction as questionable and try the next request. Charles Law wrote: Show quoteHide quote > Hi CJ > > Here is an example > > <code> > Sub Button1_Click(...) Handles ... > > Try > DoFileStuff > > Catch ex As Exception > ' This is a catch-all because we don't want > ' our button click handler to blow up > MessageBox.Show(ex.Message) > > End Try > > End Sub > > Sub DoFileStuff() > > Try > OpenFile > > WriteToFile > > Catch ex As SpecificException > ' Catch this exception because we know what to do if it occurs > > Catch ex As SomeOtherExceptionThatICanHandle > ' Catch this exception as well for the same reason. However > ' it requires a different reaction, so we catch it separately > > Finally > ' This will always execute, even if UnexpectedException is thrown > If FileIsOpen Then > CloseFile > End If > > End Try > > ' Code here will not execute if UnexpectedException is thrown, > ' so we cannot rely on closing the file here > > End Sub > </code> > > HTH > > Charles > > > "cj" <cj@nospam.nospam> wrote in message > news:%2384myMeSGHA.6084@TK2MSFTNGP14.phx.gbl... >> I guess I'll have to do some reading on finally. I'm still not sure I see >> the use. Perhaps it's how I'm using try catch. My purpose in using try >> catch is that without it, or some other error handling, if a command throws >> an exception the program halts with some garbage on the screen. I've >> written my program with try catch around statements like calls to other >> servers where something like a cable being cut might cause the line to >> throw and exception as it can not execute. In the catch I want to know >> what command is giving the problem. That'll help me know what is wrong. I >> print a custom message to indicate what code is being executed and the >> ex.message info to the screen for diagnosis. I need to know which stored >> procedure will not work, or is it the request to the remote server or did >> it try to parse the xml file and find out it wasn't a xml file? The >> presence of an error like this can mean skip the current record or it might >> mean reattempt the failed command until it starts working. >> >> In any event after the try catch the program continues to run. I test a >> flag variable or some other way to see if the previous statement threw an >> exception and make my processing decisions based on that. So my code >> after the try catch always executes--how is that different from being in >> finally? >> >> Cor Ligthert [MVP] wrote: >>> CJ, >>> >>> The statements in the finally block will be always executed unless you >>> power your computer down before that or execute the End statement. (Even >>> if there is a return in the sub than the finally will be done first). >>> >>> I hope this helps, >>> >>> Cor >>> >>> "cj" <cj@nospam.nospam> schreef in bericht >>> news:O%23fbnudSGHA.4300@TK2MSFTNGP14.phx.gbl... >>>> If I call a sub as one of the inside within a try, would the try trap >>>> errors in the sub? I hope not. My intention is only that this sub >>>> should only be run if there were no errors in the statement before it. >>>> >>>> Also I'm not sure I understand Finally. How are statements in finally >>>> different from those that follow the end try? >>>> >>>> >>>> Marina Levit [MVP] wrote: >>>>> Yes, that is what I am saying. That is the whole point of a try block. >>>>> >>>>> You wouldn't know which one it was. You would need a separate >>>>> try/catch for each line of code if you had different error handling >>>>> code depending on which exact one threw the exception. >>>>> Or if the different things threw different types of exceptions, you >>>>> could have multiple catch blocks each catching a different exception >>>>> type, and have different error handling code execute that way. >>>>> >>>>> "cj" <cj@nospam.nospam> wrote in message >>>>> news:%23rn7ZedSGHA.4740@TK2MSFTNGP14.phx.gbl... >>>>>> So are you saying if I have that if line 2 throws and exception it >>>>>> will skip 3, 4 and 5 and go straight to catch? >>>>>> >>>>>> If so, the next question is how do I know it was line 2 that threw the >>>>>> exception and not line 1 or 4? >>>>>> >>>>>> try >>>>>> 1 >>>>>> 2 >>>>>> 3 >>>>>> 4 >>>>>> 5 >>>>>> catch >>>>>> a >>>>>> end try >>>>>> >>>>>> Marina Levit [MVP] wrote: >>>>>>> That's what the Try is for. To do stuff with the assumption that >>>>>>> there are no errors. The catch is to deal with any errors. And the >>>>>>> finally is to run regardless of whether or not there were errors. >>>>>>> >>>>>>> "cj" <cj@nospam.nospam> wrote in message >>>>>>> news:uOwfvRdSGHA.5552@TK2MSFTNGP14.phx.gbl... >>>>>>>> Another wish of mine. I wish there was a way in the Try Catch >>>>>>>> structure to say if there wasn't an error to do something. Like an >>>>>>>> else statement. Try Catch Else Finally. >>>>>>>> >>>>>>>> Also because I understand Finally runs whether an error was caught >>>>>>>> or not, I haven't found a use for finally yet. >>>>>>>> > Hi Cj
> 1. is the button1_click catch catching exceptions thrown by lines inside The Catch in Button1_Click() catches any exception that 'escapes' from > dofilestuff or just if the line dofilestuff itself for some reason threw > an exception? DoFileStuff(). So, if UnexpectedException is thrown it will be caught in Button1_Click(). If SomeException is thrown it will be caught in DoFileStuff(). If DoFileStuff() rethrows it, or throws it as some other exception, then that will be caught in Button1_Click(). Otherwise, DoFileStuff() can consume the exception and retry the offending code or move on to the next iteration, if that is what is happening (the logic in DoFileStuff() would have to support this). > 2. your catching different types of exceptions. I'm catching any I wasn't trying to be prescriptive about how your exception handling should > exceptions and treating them all the same. The show must go on in my > program regardless of any exceptions. Some lines an exception on them > would be best handled by retrying the line and others by skipping to the > next iteration of the program. ie on reading from a server it'd be best > to retry untill it works while on getting a badly formated xml file from > the server I'd probably flag that transaction as questionable and try the > next request. be done. I was just trying to give an example of how Finally is useful. However, there does seem to be a case for catching some exceptions separately, and then having a catch-all to cover unexpected exceptions. You could have <code> Sub DoFileStuff() Try OpenFile WriteToFile Catch ex As SpecificException ' Catch this exception because we know what to do if it occurs Catch ex As SomeOtherExceptionThatICanHandle ' Catch this exception as well for the same reason. However ' it requires a different reaction, so we catch it separately Catch ex As Exception ' Catch all other exceptions and perform some ' default action and try to keep going Finally If FileIsOpen Then CloseFile End If End Try End Sub </code> Charles Show quoteHide quote "cj" <cj@nospam.nospam> wrote in message news:%23KxlREfSGHA.4608@tk2msftngp13.phx.gbl... >I see a couple things here. > > 1. is the button1_click catch catching exceptions thrown by lines inside > dofilestuff or just if the line dofilestuff itself for some reason threw > an exception? > > 2. your catching different types of exceptions. I'm catching any > exceptions and treating them all the same. The show must go on in my > program regardless of any exceptions. Some lines an exception on them > would be best handled by retrying the line and others by skipping to the > next iteration of the program. ie on reading from a server it'd be best > to retry untill it works while on getting a badly formated xml file from > the server I'd probably flag that transaction as questionable and try the > next request. > > > Charles Law wrote: >> Hi CJ >> >> Here is an example >> >> <code> >> Sub Button1_Click(...) Handles ... >> >> Try >> DoFileStuff >> >> Catch ex As Exception >> ' This is a catch-all because we don't want >> ' our button click handler to blow up >> MessageBox.Show(ex.Message) >> >> End Try >> >> End Sub >> >> Sub DoFileStuff() >> >> Try >> OpenFile >> >> WriteToFile >> >> Catch ex As SpecificException >> ' Catch this exception because we know what to do if it occurs >> >> Catch ex As SomeOtherExceptionThatICanHandle >> ' Catch this exception as well for the same reason. However >> ' it requires a different reaction, so we catch it separately >> >> Finally >> ' This will always execute, even if UnexpectedException is thrown >> If FileIsOpen Then >> CloseFile >> End If >> >> End Try >> >> ' Code here will not execute if UnexpectedException is thrown, >> ' so we cannot rely on closing the file here >> >> End Sub >> </code> >> >> HTH >> >> Charles >> >> >> "cj" <cj@nospam.nospam> wrote in message >> news:%2384myMeSGHA.6084@TK2MSFTNGP14.phx.gbl... >>> I guess I'll have to do some reading on finally. I'm still not sure I >>> see the use. Perhaps it's how I'm using try catch. My purpose in using >>> try catch is that without it, or some other error handling, if a command >>> throws an exception the program halts with some garbage on the screen. >>> I've written my program with try catch around statements like calls to >>> other servers where something like a cable being cut might cause the >>> line to throw and exception as it can not execute. In the catch I want >>> to know what command is giving the problem. That'll help me know what >>> is wrong. I print a custom message to indicate what code is being >>> executed and the ex.message info to the screen for diagnosis. I need to >>> know which stored procedure will not work, or is it the request to the >>> remote server or did it try to parse the xml file and find out it wasn't >>> a xml file? The presence of an error like this can mean skip the >>> current record or it might mean reattempt the failed command until it >>> starts working. >>> >>> In any event after the try catch the program continues to run. I test a >>> flag variable or some other way to see if the previous statement threw >>> an exception and make my processing decisions based on that. So my code >>> after the try catch always executes--how is that different from being in >>> finally? >>> >>> Cor Ligthert [MVP] wrote: >>>> CJ, >>>> >>>> The statements in the finally block will be always executed unless you >>>> power your computer down before that or execute the End statement. >>>> (Even if there is a return in the sub than the finally will be done >>>> first). >>>> >>>> I hope this helps, >>>> >>>> Cor >>>> >>>> "cj" <cj@nospam.nospam> schreef in bericht >>>> news:O%23fbnudSGHA.4300@TK2MSFTNGP14.phx.gbl... >>>>> If I call a sub as one of the inside within a try, would the try trap >>>>> errors in the sub? I hope not. My intention is only that this sub >>>>> should only be run if there were no errors in the statement before it. >>>>> >>>>> Also I'm not sure I understand Finally. How are statements in finally >>>>> different from those that follow the end try? >>>>> >>>>> >>>>> Marina Levit [MVP] wrote: >>>>>> Yes, that is what I am saying. That is the whole point of a try >>>>>> block. >>>>>> >>>>>> You wouldn't know which one it was. You would need a separate >>>>>> try/catch for each line of code if you had different error handling >>>>>> code depending on which exact one threw the exception. >>>>>> Or if the different things threw different types of exceptions, you >>>>>> could have multiple catch blocks each catching a different exception >>>>>> type, and have different error handling code execute that way. >>>>>> >>>>>> "cj" <cj@nospam.nospam> wrote in message >>>>>> news:%23rn7ZedSGHA.4740@TK2MSFTNGP14.phx.gbl... >>>>>>> So are you saying if I have that if line 2 throws and exception it >>>>>>> will skip 3, 4 and 5 and go straight to catch? >>>>>>> >>>>>>> If so, the next question is how do I know it was line 2 that threw >>>>>>> the exception and not line 1 or 4? >>>>>>> >>>>>>> try >>>>>>> 1 >>>>>>> 2 >>>>>>> 3 >>>>>>> 4 >>>>>>> 5 >>>>>>> catch >>>>>>> a >>>>>>> end try >>>>>>> >>>>>>> Marina Levit [MVP] wrote: >>>>>>>> That's what the Try is for. To do stuff with the assumption that >>>>>>>> there are no errors. The catch is to deal with any errors. And the >>>>>>>> finally is to run regardless of whether or not there were errors. >>>>>>>> >>>>>>>> "cj" <cj@nospam.nospam> wrote in message >>>>>>>> news:uOwfvRdSGHA.5552@TK2MSFTNGP14.phx.gbl... >>>>>>>>> Another wish of mine. I wish there was a way in the Try Catch >>>>>>>>> structure to say if there wasn't an error to do something. Like >>>>>>>>> an else statement. Try Catch Else Finally. >>>>>>>>> >>>>>>>>> Also because I understand Finally runs whether an error was caught >>>>>>>>> or not, I haven't found a use for finally yet. >>>>>>>>> >> Thanks.
Charles Law wrote: Show quoteHide quote > Hi Cj > >> 1. is the button1_click catch catching exceptions thrown by lines inside >> dofilestuff or just if the line dofilestuff itself for some reason threw >> an exception? > > The Catch in Button1_Click() catches any exception that 'escapes' from > DoFileStuff(). So, if UnexpectedException is thrown it will be caught in > Button1_Click(). If SomeException is thrown it will be caught in > DoFileStuff(). If DoFileStuff() rethrows it, or throws it as some other > exception, then that will be caught in Button1_Click(). Otherwise, > DoFileStuff() can consume the exception and retry the offending code or move > on to the next iteration, if that is what is happening (the logic in > DoFileStuff() would have to support this). > >> 2. your catching different types of exceptions. I'm catching any >> exceptions and treating them all the same. The show must go on in my >> program regardless of any exceptions. Some lines an exception on them >> would be best handled by retrying the line and others by skipping to the >> next iteration of the program. ie on reading from a server it'd be best >> to retry untill it works while on getting a badly formated xml file from >> the server I'd probably flag that transaction as questionable and try the >> next request. > > I wasn't trying to be prescriptive about how your exception handling should > be done. I was just trying to give an example of how Finally is useful. > However, there does seem to be a case for catching some exceptions > separately, and then having a catch-all to cover unexpected exceptions. You > could have > > <code> > Sub DoFileStuff() > > Try > OpenFile > > WriteToFile > > Catch ex As SpecificException > ' Catch this exception because we know what to do if it occurs > > Catch ex As SomeOtherExceptionThatICanHandle > ' Catch this exception as well for the same reason. However > ' it requires a different reaction, so we catch it separately > > Catch ex As Exception > ' Catch all other exceptions and perform some > ' default action and try to keep going > > Finally > If FileIsOpen Then > CloseFile > End If > > End Try > > End Sub > </code> > > Charles > > "cj" <cj@nospam.nospam> wrote in message > news:%23KxlREfSGHA.4608@tk2msftngp13.phx.gbl... >> I see a couple things here. >> >> 1. is the button1_click catch catching exceptions thrown by lines inside >> dofilestuff or just if the line dofilestuff itself for some reason threw >> an exception? >> >> 2. your catching different types of exceptions. I'm catching any >> exceptions and treating them all the same. The show must go on in my >> program regardless of any exceptions. Some lines an exception on them >> would be best handled by retrying the line and others by skipping to the >> next iteration of the program. ie on reading from a server it'd be best >> to retry untill it works while on getting a badly formated xml file from >> the server I'd probably flag that transaction as questionable and try the >> next request. >> >> >> Charles Law wrote: >>> Hi CJ >>> >>> Here is an example >>> >>> <code> >>> Sub Button1_Click(...) Handles ... >>> >>> Try >>> DoFileStuff >>> >>> Catch ex As Exception >>> ' This is a catch-all because we don't want >>> ' our button click handler to blow up >>> MessageBox.Show(ex.Message) >>> >>> End Try >>> >>> End Sub >>> >>> Sub DoFileStuff() >>> >>> Try >>> OpenFile >>> >>> WriteToFile >>> >>> Catch ex As SpecificException >>> ' Catch this exception because we know what to do if it occurs >>> >>> Catch ex As SomeOtherExceptionThatICanHandle >>> ' Catch this exception as well for the same reason. However >>> ' it requires a different reaction, so we catch it separately >>> >>> Finally >>> ' This will always execute, even if UnexpectedException is thrown >>> If FileIsOpen Then >>> CloseFile >>> End If >>> >>> End Try >>> >>> ' Code here will not execute if UnexpectedException is thrown, >>> ' so we cannot rely on closing the file here >>> >>> End Sub >>> </code> >>> >>> HTH >>> >>> Charles >>> >>> >>> "cj" <cj@nospam.nospam> wrote in message >>> news:%2384myMeSGHA.6084@TK2MSFTNGP14.phx.gbl... >>>> I guess I'll have to do some reading on finally. I'm still not sure I >>>> see the use. Perhaps it's how I'm using try catch. My purpose in using >>>> try catch is that without it, or some other error handling, if a command >>>> throws an exception the program halts with some garbage on the screen. >>>> I've written my program with try catch around statements like calls to >>>> other servers where something like a cable being cut might cause the >>>> line to throw and exception as it can not execute. In the catch I want >>>> to know what command is giving the problem. That'll help me know what >>>> is wrong. I print a custom message to indicate what code is being >>>> executed and the ex.message info to the screen for diagnosis. I need to >>>> know which stored procedure will not work, or is it the request to the >>>> remote server or did it try to parse the xml file and find out it wasn't >>>> a xml file? The presence of an error like this can mean skip the >>>> current record or it might mean reattempt the failed command until it >>>> starts working. >>>> >>>> In any event after the try catch the program continues to run. I test a >>>> flag variable or some other way to see if the previous statement threw >>>> an exception and make my processing decisions based on that. So my code >>>> after the try catch always executes--how is that different from being in >>>> finally? >>>> >>>> Cor Ligthert [MVP] wrote: >>>>> CJ, >>>>> >>>>> The statements in the finally block will be always executed unless you >>>>> power your computer down before that or execute the End statement. >>>>> (Even if there is a return in the sub than the finally will be done >>>>> first). >>>>> >>>>> I hope this helps, >>>>> >>>>> Cor >>>>> >>>>> "cj" <cj@nospam.nospam> schreef in bericht >>>>> news:O%23fbnudSGHA.4300@TK2MSFTNGP14.phx.gbl... >>>>>> If I call a sub as one of the inside within a try, would the try trap >>>>>> errors in the sub? I hope not. My intention is only that this sub >>>>>> should only be run if there were no errors in the statement before it. >>>>>> >>>>>> Also I'm not sure I understand Finally. How are statements in finally >>>>>> different from those that follow the end try? >>>>>> >>>>>> >>>>>> Marina Levit [MVP] wrote: >>>>>>> Yes, that is what I am saying. That is the whole point of a try >>>>>>> block. >>>>>>> >>>>>>> You wouldn't know which one it was. You would need a separate >>>>>>> try/catch for each line of code if you had different error handling >>>>>>> code depending on which exact one threw the exception. >>>>>>> Or if the different things threw different types of exceptions, you >>>>>>> could have multiple catch blocks each catching a different exception >>>>>>> type, and have different error handling code execute that way. >>>>>>> >>>>>>> "cj" <cj@nospam.nospam> wrote in message >>>>>>> news:%23rn7ZedSGHA.4740@TK2MSFTNGP14.phx.gbl... >>>>>>>> So are you saying if I have that if line 2 throws and exception it >>>>>>>> will skip 3, 4 and 5 and go straight to catch? >>>>>>>> >>>>>>>> If so, the next question is how do I know it was line 2 that threw >>>>>>>> the exception and not line 1 or 4? >>>>>>>> >>>>>>>> try >>>>>>>> 1 >>>>>>>> 2 >>>>>>>> 3 >>>>>>>> 4 >>>>>>>> 5 >>>>>>>> catch >>>>>>>> a >>>>>>>> end try >>>>>>>> >>>>>>>> Marina Levit [MVP] wrote: >>>>>>>>> That's what the Try is for. To do stuff with the assumption that >>>>>>>>> there are no errors. The catch is to deal with any errors. And the >>>>>>>>> finally is to run regardless of whether or not there were errors. >>>>>>>>> >>>>>>>>> "cj" <cj@nospam.nospam> wrote in message >>>>>>>>> news:uOwfvRdSGHA.5552@TK2MSFTNGP14.phx.gbl... >>>>>>>>>> Another wish of mine. I wish there was a way in the Try Catch >>>>>>>>>> structure to say if there wasn't an error to do something. Like >>>>>>>>>> an else statement. Try Catch Else Finally. >>>>>>>>>> >>>>>>>>>> Also because I understand Finally runs whether an error was caught >>>>>>>>>> or not, I haven't found a use for finally yet. >>>>>>>>>> > >
Show quote
Hide quote
> I guess I'll have to do some reading on finally. I'm still not sure I As COR indicated, the finally block should be used to close resources and > see the use. Perhaps it's how I'm using try catch. My purpose in > using try catch is that without it, or some other error handling, if a > command throws an exception the program halts with some garbage on the > screen. I've written my program with try catch around statements like > calls to other servers where something like a cable being cut might > cause the line to throw and exception as it can not execute. In the > catch I want to know what command is giving the problem. That'll help > me know what is wrong. I print a custom message to indicate what code > is being executed and the ex.message info to the screen for diagnosis. > I need to know which stored procedure will not work, or is it the > request to the remote server or did it try to parse the xml file and > find out it wasn't a xml file? The presence of an error like this can > mean skip the current record or it might mean reattempt the failed > command until it starts working. do other necessary cleanup to get your program back to a valid state. You would want to make sure to clean the resources regardless of whether a exception is thrown. Consider the following pseudocode: dim cn as new Connection try cn.open catch messagebox.show("Problem opening connection") end try cn.dispose cn.close In this case, the connection (an expensive resource) is left open if the exception is thrown. As an alternative, you can do the following dim cn as new Connection try cn.open catch messagebox.show("Problem opening connection") finally cn.close cn.dispose end try In this case, we are assured that the connection will be closed. Starting with VB2005, we can change this as follows: Using cn as new Connection try cn.open catch messagebox.show("Problem with connection") end try end using Now we are assured that the connection is properly handled as the Using block handles the dispose for us and closes the connection. Now, if we want to simply let the exception bubble up to a calling method, we can trim this down to: Using cn as new Connection cn.open end using An exception will still be thrown, but the resource will be released correctly. Jim Wooley http://devauthority.com/blogs/jwooley Give me an example of an exception that could be thrown that still
allowed the db connection to open. Honestly, I'd like to know. I'm sure there are some but it seems to me the most likely reason that line would throw and exception is it couldn't open the db. second, assume it didn't open the db and then you fall to the finally section and you try to close a db that isn't open. wouldn't this also throw and exception? Jim Wooley wrote: Show quoteHide quote >> I guess I'll have to do some reading on finally. I'm still not sure I >> see the use. Perhaps it's how I'm using try catch. My purpose in >> using try catch is that without it, or some other error handling, if a >> command throws an exception the program halts with some garbage on the >> screen. I've written my program with try catch around statements like >> calls to other servers where something like a cable being cut might >> cause the line to throw and exception as it can not execute. In the >> catch I want to know what command is giving the problem. That'll help >> me know what is wrong. I print a custom message to indicate what code >> is being executed and the ex.message info to the screen for diagnosis. >> I need to know which stored procedure will not work, or is it the >> request to the remote server or did it try to parse the xml file and >> find out it wasn't a xml file? The presence of an error like this can >> mean skip the current record or it might mean reattempt the failed >> command until it starts working. > > As COR indicated, the finally block should be used to close resources > and do other necessary cleanup to get your program back to a valid > state. You would want to make sure to clean the resources regardless of > whether a exception is thrown. Consider the following pseudocode: > > dim cn as new Connection > try > cn.open > catch > messagebox.show("Problem opening connection") > end try > > cn.dispose > cn.close > > In this case, the connection (an expensive resource) is left open if the > exception is thrown. As an alternative, you can do the following > > dim cn as new Connection > try > cn.open > catch > messagebox.show("Problem opening connection") > finally > cn.close > cn.dispose > end try > > In this case, we are assured that the connection will be closed. > Starting with VB2005, we can change this as follows: > > Using cn as new Connection > try > cn.open > catch > messagebox.show("Problem with connection") > end try > end using > > Now we are assured that the connection is properly handled as the Using > block handles the dispose for us and closes the connection. Now, if we > want to simply let the exception bubble up to a calling method, we can > trim this down to: > > Using cn as new Connection > cn.open > end using > > An exception will still be thrown, but the resource will be released > correctly. > > Jim Wooley > http://devauthority.com/blogs/jwooley > > > Give me an example of an exception that could be thrown that still Ok, I was afraid someone would catch that one. I was trying to be terse while > allowed the db connection to open. Honestly, I'd like to know. I'm > sure there are some but it seems to me the most likely reason that > line would throw and exception is it couldn't open the db. > > second, assume it didn't open the db and then you fall to the finally > section and you try to close a db that isn't open. wouldn't this also > throw and exception? illustrating the finally portion. Is the following better: >> dim cn as new Connection Throw New ApplicationException>> try >> cn.open Show quoteHide quote >> catch >> messagebox.show("Problem after opening connection") >> finally >> cn.close >> cn.dispose >> end try >> Jim Wooley >> http://devauthority.com/blogs/jwooley At least it must not have been a dumb question. These possible errors
are turning into a vicious loop in my head. Unfortunately I don't get how your line addition helps things. I'll have to add this to the many areas to research when I get time. Jim Wooley wrote: Show quoteHide quote >> Give me an example of an exception that could be thrown that still >> allowed the db connection to open. Honestly, I'd like to know. I'm >> sure there are some but it seems to me the most likely reason that >> line would throw and exception is it couldn't open the db. >> >> second, assume it didn't open the db and then you fall to the finally >> section and you try to close a db that isn't open. wouldn't this also >> throw and exception? > > Ok, I was afraid someone would catch that one. I was trying to be terse > while illustrating the finally portion. Is the following better: > >>> dim cn as new Connection >>> try >>> cn.open > Throw New ApplicationException >>> catch >>> messagebox.show("Problem after opening connection") >>> finally >>> cn.close >>> cn.dispose >>> end try > >>> Jim Wooley >>> http://devauthority.com/blogs/jwooley > > > At least it must not have been a dumb question. These possible errors Ok. In the new addition, there is some other exception that is thrown other > are turning into a vicious loop in my head. > Unfortunately I don't get how your line addition helps things. than creating the connection. It could be due to a null in the database that is not handled by the data reader, a column that is removed from the database, a database timeout, anything. The key here being, you need to reclaim the resource and not just leave it hanging. The best ways to do this are in the Finally block or with the Using statement. Jim Wooley Show quoteHide quote >>>> dim cn as new Connection >>>> try >>>> cn.open >> Throw New ApplicationException >> >>>> catch >>>> messagebox.show("Problem after opening connection") >>>> finally >>>> cn.close >>>> cn.dispose >>>> end try >>>> Jim Wooley >>>> http://devauthority.com/blogs/jwooley > dim cn as new Connection No it isn't. The code following the End Try will execute. Bad example in > try > cn.open > catch > messagebox.show("Problem opening connection") > end try > > cn.dispose > cn.close > > In this case, the connection (an expensive resource) is left open if the > exception is thrown. several ways: if an exception is thrown then one presumes that the connection failed to open, so no resource is used. But, in any case, the code following the End Try will execute, so if the connection had opened and then thrown an exception, it would have been disposed and closed. [Finally, surely the connection should be closed and then disposed] Charles Show quoteHide quote "Jim Wooley" <jimNOSPAMwooley@hotmail.com> wrote in message news:24f81e8e3ee28c817e8e6dd4e74@msnews.microsoft.com... >> I guess I'll have to do some reading on finally. I'm still not sure I >> see the use. Perhaps it's how I'm using try catch. My purpose in >> using try catch is that without it, or some other error handling, if a >> command throws an exception the program halts with some garbage on the >> screen. I've written my program with try catch around statements like >> calls to other servers where something like a cable being cut might >> cause the line to throw and exception as it can not execute. In the >> catch I want to know what command is giving the problem. That'll help >> me know what is wrong. I print a custom message to indicate what code >> is being executed and the ex.message info to the screen for diagnosis. >> I need to know which stored procedure will not work, or is it the >> request to the remote server or did it try to parse the xml file and >> find out it wasn't a xml file? The presence of an error like this can >> mean skip the current record or it might mean reattempt the failed >> command until it starts working. > > As COR indicated, the finally block should be used to close resources and > do other necessary cleanup to get your program back to a valid state. You > would want to make sure to clean the resources regardless of whether a > exception is thrown. Consider the following pseudocode: > > dim cn as new Connection > try > cn.open > catch > messagebox.show("Problem opening connection") > end try > > cn.dispose > cn.close > > In this case, the connection (an expensive resource) is left open if the > exception is thrown. As an alternative, you can do the following > > dim cn as new Connection > try > cn.open > catch > messagebox.show("Problem opening connection") > finally > cn.close > cn.dispose > end try > > In this case, we are assured that the connection will be closed. Starting > with VB2005, we can change this as follows: > > Using cn as new Connection > try > cn.open > catch > messagebox.show("Problem with connection") > end try > end using > > Now we are assured that the connection is properly handled as the Using > block handles the dispose for us and closes the connection. Now, if we > want to simply let the exception bubble up to a calling method, we can > trim this down to: > > Using cn as new Connection > cn.open > end using > > An exception will still be thrown, but the resource will be released > correctly. > > Jim Wooley > http://devauthority.com/blogs/jwooley > > CJ,
So my code > after the try catch always executes--how is that different from being in Put as first statement in your try catch finallly a return (direct after the > finally? > try), and debug it, than you see it. Cor
Show quote
Hide quote
> > you could have several catch statements - If each line could throw a> > If so, the next question is how do I know it was line 2 that threw the > > exception and not line 1 or 4? > > > > try > > 1 > > 2 > > 3 > > 4 > > 5 > > catch > > a > > end try > > > > Marina Levit [MVP] wrote: > >> That's what the Try is for. To do stuff with the assumption that there > >> are no errors. The catch is to deal with any errors. And the finally is > >> to run regardless of whether or not there were errors. different type of exception, then the appropriate catch statement would be used. following is cut-n-paste from msdn Try NextCentury = DateAdd("yyyy", 100, GivenDate) Catch ThisExcep As System.ArgumentException ' At least one argument has an invalid value. Catch ThisExcep As ArgumentOutOfRangeException ' The result is later than December 31, 9999. Catch ThisExcep As InvalidCastException ' GivenDate cannot be interpreted As a date/time. Catch ' An unforeseen exception has occurred. Finally ' This block is always executed before leaving. End Try Not too sure if I understand the question.
The mainline of the Try block is the implied 'do this if no error' branch, with the the catch occuring only if an exception occurs. Do you have an example of the functionality that you would like to see. As for the finally One example is to close files e.g. Dim fs As FileStream Dim reader As TextReader Try fs = New FileStream("test.txt", FileMode.Open) reader = New StreamReader(fs) While True Dim str As String = reader.ReadLine If (str Is Nothing) Then Exit While End If Trace.WriteLine(str) End While Finally If Not fs Is Nothing Then fs.Close() End If End Try Say something went wrong during a read (or if we we doing something more complicated with the input than just dumping it to trace) then when we the exception occurs we want the filestream to be closed. We also want it to be closed during the normal flow. hth, Alan Your right Marina Levit has already set me straight. Only remaining
downside is I wouldn't know which line caused the exception. Thanks for the reply. AlanT wrote: Show quoteHide quote > Not too sure if I understand the question. > > The mainline of the Try block is the implied 'do this if no error' > branch, with the the catch occuring only if an exception occurs. > > Do you have an example of the functionality that you would like to see. > > > As for the finally > > One example is to close files > > e.g. > > Dim fs As FileStream > Dim reader As TextReader > > Try > > fs = New FileStream("test.txt", FileMode.Open) > reader = New StreamReader(fs) > > While True > > Dim str As String = reader.ReadLine > If (str Is Nothing) Then > Exit While > End If > > Trace.WriteLine(str) > > End While > > Finally > > If Not fs Is Nothing Then > fs.Close() > End If > > End Try > > Say something went wrong during a read (or if we we doing something > more complicated with the input than just dumping it to trace) then > when we the exception occurs we want the filestream to be closed. We > also want it to be closed during the normal flow. > > > hth, > Alan > > Your right Marina Levit has already set me straight. Only remaining You CAN get the line that caused the exception if you number your lines (like > downside is I wouldn't know which line caused the exception. Thanks > for the reply. old Basic). The following is perfectly acceptable VB.Net code: 10: REM This program doesn't do much 20: Try 30: REM Throw an error 40: Throw New DivideByZeroException 50: Catch ex As DivideByZeroException 60: Console.WriteLine("Error occured in line: " & Erl()) 70: End Try 80: Console.ReadLine() The output is: Error occured in line: 40 The upside is: the line numbers are retained when you compile in release mode. The down side is that there is a performance hit, so you would only want to do this when it is essential you know the line causing the problem and speed is not as important. Jim Wooley http://devauthority.com/blogs/jwooley/archive/2005/12/21/661.aspx Hi,
Is there something I'm missing here, Jim ? Why go to such an extent when the line no. can be determined easily. If I simply include the following line within my Catch block : : Catch ex as Exception: Console.WriteLine("ex.ToString()") Finally... I can get the output which gives the Line no. at which the error occurred. This is because using ToString() here appends the Message Property and the StackTrace property (which contains the Line no.) and displays it as a string. So, why should we have to add in Line nos. manually to the code ? Regards, Cerebrus. My guess would be he assumes, and I expect I would if I used this
approach, make a decision on what to do in the catch based on the line number catch tells me the error occurred on. So I need at coding time to see what line is what number to program in specific actions to be taken for specific lines. Sorry Jim, line numbers are on thing I don't want to bring back. Cerebrus wrote: Show quoteHide quote > Hi, > > Is there something I'm missing here, Jim ? Why go to such an extent > when the line no. can be determined easily. If I simply include the > following line within my Catch block : > > : > : > Catch ex as Exception > Console.WriteLine("ex.ToString()") > Finally... > > > I can get the output which gives the Line no. at which the error > occurred. This is because using ToString() here appends the Message > Property and the StackTrace property (which contains the Line no.) and > displays it as a string. > > So, why should we have to add in Line nos. manually to the code ? > > Regards, > > Cerebrus. > It could be also because he tries to catch global errors instead of having
multiple catch clauses. IMO he's best bet for now would be to give a close look at the Try statement... -- Patrice "cj" <cj@nospam.nospam> a écrit dans le message de news: uUbJEPeSGHA.***@TK2MSFTNGP12.phx.gbl...Show quoteHide quote > My guess would be he assumes, and I expect I would if I used this > approach, make a decision on what to do in the catch based on the line > number catch tells me the error occurred on. So I need at coding time to > see what line is what number to program in specific actions to be taken > for specific lines. > > Sorry Jim, line numbers are on thing I don't want to bring back. > > > Cerebrus wrote: >> Hi, >> >> Is there something I'm missing here, Jim ? Why go to such an extent >> when the line no. can be determined easily. If I simply include the >> following line within my Catch block : >> >> : >> : >> Catch ex as Exception >> Console.WriteLine("ex.ToString()") >> Finally... >> >> >> I can get the output which gives the Line no. at which the error >> occurred. This is because using ToString() here appends the Message >> Property and the StackTrace property (which contains the Line no.) and >> displays it as a string. >> >> So, why should we have to add in Line nos. manually to the code ? >> >> Regards, >> >> Cerebrus. >> > Hi, The difference is the release build vs the debug build. The line numbers > > Is there something I'm missing here, Jim ? Why go to such an extent > when the line no. can be determined easily. are stripped from the stack trace in a release build. I didn't mean to say that you should use them, just that you could. Jim Wooley (new post: http://devauthority.com/blogs/jwooley/archive/2006/03/17/795.aspx) You can get line numbers, but that is only good for showing error messages.
It's not like you can in code figure out which function call caused the error - unless you start hard coding if statements to look for specific line numbers - but that isn't something you would ever want to do. cj wanted to figure out which line of code was causing the problem, to presumably either have different error handling code, or ignore the error, etc. That isn't something the stack trace information can realistically help with. Not to mention, line numbers come up only when compiled in debug mode. Show quoteHide quote "Jim Wooley" <jimNOSPAMwooley@hotmail.com> wrote in message news:24f81e8e3e698c817caf419aded@msnews.microsoft.com... >> Your right Marina Levit has already set me straight. Only remaining >> downside is I wouldn't know which line caused the exception. Thanks >> for the reply. > > You CAN get the line that caused the exception if you number your lines > (like old Basic). The following is perfectly acceptable VB.Net code: > > 10: REM This program doesn't do much > 20: Try > 30: REM Throw an error > 40: Throw New DivideByZeroException > 50: Catch ex As DivideByZeroException > 60: Console.WriteLine("Error occured in line: " & Erl()) > 70: End Try > 80: Console.ReadLine() > > The output is: > > Error occured in line: 40 > > The upside is: the line numbers are retained when you compile in release > mode. The down side is that there is a performance hit, so you would only > want to do this when it is essential you know the line causing the problem > and speed is not as important. > > Jim Wooley > http://devauthority.com/blogs/jwooley/archive/2005/12/21/661.aspx > > > You can get line numbers, but that is only good for showing error I think we can agree that using the old On Error GOTO...Resume Next method > messages. It's not like you can in code figure out which function call > caused the error - unless you start hard coding if statements to look > for specific line numbers - but that isn't something you would ever > want to do. > > cj wanted to figure out which line of code was causing the problem, to > presumably either have different error handling code, or ignore the > error, etc. That isn't something the stack trace information can > realistically help with. is far from ideal. Structured exception handling is a better, more robust mechanism and would be the prefered method. I am not advocating using the line numbers and ERL(), more-so mentioning that it is possible. > Not to mention, line numbers come up only when compiled in debug mode. ERR. Sorry. Thanks for playing. I just tested it in VS2005 and the line number is retained in a release mode when hard coded as in my sample. You do not get the line numbers in the stack trace, but ERL() will still report the line number if it is included in the source code. Hence the additional overhead. I just checked the sample code with Reflector and the VB compiler is adding a variable to track the line numbers and incrementing it interspersed in the code, similar to inserting a trace.write method in the body of the code. Here's the dis-assembled version of the previous sample: Public Shared Sub Main() Dim num1 As Integer = 10 num1 = 20 Try num1 = 30 num1 = 40 Throw New DivideByZeroException Catch exception2 As DivideByZeroException ProjectData.SetProjectError(exception2, num1) Dim exception1 As DivideByZeroException = exception2 num1 = 60 Console.WriteLine(("Error occured in line: " & Conversions.ToString(Information.Erl))) num1 = 70 ProjectData.ClearProjectError End Try num1 = 80 Console.ReadLine As you can see, it works but is far from elegant and the performance implications are not good. I was speaking about using the StackTrace and getting line numbers, not ERL.
I never mentioned it, and I've never heard of it. And sort of glad I hadn't - seems like a horrible way to let people check which line number caused an error, and hard coding line numbers in their error handling code. Show quoteHide quote "Jim Wooley" <jimNOSPAMwooley@hotmail.com> wrote in message news:24f81e8e3ec58c817e437c3c907@msnews.microsoft.com... >> You can get line numbers, but that is only good for showing error >> messages. It's not like you can in code figure out which function call >> caused the error - unless you start hard coding if statements to look >> for specific line numbers - but that isn't something you would ever >> want to do. >> >> cj wanted to figure out which line of code was causing the problem, to >> presumably either have different error handling code, or ignore the >> error, etc. That isn't something the stack trace information can >> realistically help with. > > I think we can agree that using the old On Error GOTO...Resume Next method > is far from ideal. Structured exception handling is a better, more robust > mechanism and would be the prefered method. I am not advocating using the > line numbers and ERL(), more-so mentioning that it is possible. > >> Not to mention, line numbers come up only when compiled in debug mode. > > ERR. Sorry. Thanks for playing. I just tested it in VS2005 and the line > number is retained in a release mode when hard coded as in my sample. You > do not get the line numbers in the stack trace, but ERL() will still > report the line number if it is included in the source code. Hence the > additional overhead. I just checked the sample code with Reflector and the > VB compiler is adding a variable to track the line numbers and > incrementing it interspersed in the code, similar to inserting a > trace.write method in the body of the code. Here's the dis-assembled > version of the previous sample: > > Public Shared Sub Main() > Dim num1 As Integer = 10 > num1 = 20 > Try num1 = 30 > num1 = 40 > Throw New DivideByZeroException > Catch exception2 As DivideByZeroException > ProjectData.SetProjectError(exception2, num1) > Dim exception1 As DivideByZeroException = exception2 > num1 = 60 > Console.WriteLine(("Error occured in line: " & > Conversions.ToString(Information.Erl))) > num1 = 70 > ProjectData.ClearProjectError > End Try > num1 = 80 > Console.ReadLine > > As you can see, it works but is far from elegant and the performance > implications are not good. > > The stack trace from the exception will show you where the exception
occurred. hth, Alan.
CSV File Import
error detection Select case wildcard Listview subitems Dropdownlist Chain Visible Vbnet 2005 and databases + database bug ?? About ListView1.Items.Contains Zip files using VB6 Need explorer treeview control with checkbox converting ansi to utf8 format - is there anything wrong with it ? urgently requires help |
|||||||||||||||||||||||