VB.NET Try / Catch / When - Stay Away or Use It?

VB.NET has, unlike C #, a conditional exception exception function in the Try / Catch / finally block.

It seemed to me that I read somewhere that this is usually a bad practice, because it encourages people to invest (business logic) in handling exception handling and that you basically get the famous GoTo .

 Try // Do something Catch ex As MyException When [condition] // End Try 

So, are there legitimate uses of the When function, or should we avoid this?

This has probably already been answered, but I couldn’t find anything relevant because β€œWhen” is a pretty bad search keyword.

+6
source share
1 answer

The usual case that I can think of is when you only want to catch a specific exception based on the contents of that exception. For instance:.

 Try // Do something Catch ex As SqlException When ex.Number = 547 // Constraint Violation End Try 

Which saves you from catching all SqlException s, and then examining the Number property, and then throwing the exception again if it doesn't match.

See also Good and Bad Exception Filters :

For example, if you have a fairly general exception, such as a COMException, you usually want to catch this when it represents a specific HRESULT. For example, you want it to be ignored when it presents E_FAIL, but you want to catch it when it presents E_ACCESSDEINED, because you have an alternative for this case. Here is a perfectly reasonable conditional catch clause:

 Catch ex As System.Runtime.InteropServices.COMException When ex.ErrorCode() = &H80070005 

An alternative is to place the condition in the catch block and throw an exception if it does not meet your criteria. For instance:

 Catch ex As System.Runtime.InteropServices.COMException If (ex.ErrorCode != &H80070005) Then Throw 

Logically, this catch / rethrow pattern does the same thing as a filter, but there is a subtle and important difference. If the exception is not handled, then the state of the program is different from two. In the case of catch / rethrow, an unhandled exception will appear from the Throw statement in the catch block. After that, there will be no call stack, and all finally blocks until the catch clause are executed. Both make debugging more difficult. In the case of a filter, an exception is not processed from the point of the initial throw, and no state of the program has been changed by the final sentences.

+5
source

Source: https://habr.com/ru/post/956074/


All Articles