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
What happens to the call stack if you use Throw ex instead of Throw?
Using
Throwwithout a parameter preserves the original call stack — the one where the exception occurred. If you useThrow 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.
Story
In a large banking project, developers used
Throw exto 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,
Throwwas used to rethrow SqlExceptions, but in some cases, the code auto-formatting tool automatically replaced it withThrow 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
Throwwithout 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.