简体   繁体   中英

Modern approach to 'on error goto [catch-all] label' in C#

From my research, this question was asked a lot in the early days of dot net, but IMHO a lot of the responses were a bit snarky and 'thats the way we do it now' style. Lets see if the net has grown up a bit.

Example Circa 1992:

Sub Main()
On Error GoTo ErrHand
....Code Here
End Sub

ErrHand:
  ' raise error nicely here inc error no, desc, line & character pos
End Sub

Clunky as it was, the 'on error goto [catch-all] label' approach available to VB6 had a use, which was to catch unexpected exceptions and report them. It could report the error number & description, with the module, line number and character position of the exception. Diligent developers would, of course, code for anticipated exceptions and business logic exceptions. The on-error thing was a very useful answer to not having a crystal ball.

My C# buddies tell me to use try-catch, but at the same time they say folk-lore says not to put a big try-catch into each method because that is bad practice.

But when I inquire as to the exact source of the folk-lore there is no answer.

So - what is the 2016 answer for the C# equiv of the VB6 'on error goto [catch-all] label' construct, and why can't I have a standardised try-catch wrapping the contents of each module to effect the same unanticipated exception handling?

When you don't know the nature of the error, what can you sensibly do? Just about the only sensible thing to do is to try to log the error and then shut down - you can't reason about the state of the program, all you know is that it's not what you thought it was.

As such, the best place to handle this situation is in AppDomain.UnhandledException or similar (note that the documentation discusses other approaches which may apply for some specific application models).

That way, you write the code once - not once per function . (Unless you're writing small "toy" applications, it's vanishingly rare to write single-threaded applications these days, and the On Error Goto pattern would have to, at the least, be repeated for every function that acts as an entry point for a new thread)

Anywhere else, if you're writing a try / catch , it should be because you have a specific strategy for dealing with and recovering from the error situation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM