ProgrammingVB.NET Developer, Backend Developer

How is exception handling and rethrowing implemented in Visual Basic? What nuances exist between the `Throw` and `Throw ex` statements, and what are the dangers of incorrectly rethrowing an exception?

Pass interviews with Hintsage AI assistant

Answer

In Visual Basic, exception handling uses the Try...Catch...Finally block. To rethrow an exception after catching it — i.e., to pass it further up the call stack — the Throw or Throw ex statement is used.

Differences:

  • Throw (without a parameter) rethrows the current exception, preserving the original call stack.
  • Throw ex throws the exception object but resets the call stack — losing information about where the problem actually occurred.

It is recommended to use Throw without parameters for correct exception rethrowing if the exception has not been modified.

Correct rethrowing example:

Try DangerousOperation() Catch ex As Exception ' Logging... Throw ' call stack preserved End Try

Incorrect way:

Try DangerousOperation() Catch ex As Exception Throw ex ' call stack reset, diagnosis complicated End Try

Trick question

What happens to the call stack if you use Throw ex instead of Throw?

Using Throw without a parameter preserves the original call stack — the one where the exception occurred. If you use Throw ex, the stack starts from the current line, and the original point of occurrence is lost. This complicates debugging as you won't see which part of the code caused the problem.

Examples of real errors due to ignorance of the nuances


Story

In a large banking project, developers used Throw ex to throw logic errors. Upon analyzing the logs, it became impossible to determine the point of exception occurrence because they lacked proper tracing.


Story

Inside the data access layer, Throw was used to rethrow SqlExceptions, but in some cases, the code auto-formatting tool automatically replaced it with Throw ex. This broke the automatic data extraction system from logs and increased response time to incidents.


Story

Attempting to modify an Exception object and rethrow it with Throw without parameters resulted in the changes not being reflected in the logs — only explicitly creating a new exception object with the original one as InnerException helped.