In this article I will explain with an example, how to use Response.Redirect, Response.End and Server.Transfer in Try Catch Finally block in ASP.Net.
Response.Redirect, Response.End and Server.Transfer functions raise ThreadAbortException whenever they are called inside Try Catch Finally block in ASP.Net.
Problem
When one uses Response.Redirect, Response.End or Server.Transfer in Try Catch Finally block then always the Catch block is executed.
Cause
The above problem occurs because an exception of type ThreadAbortException is raised when the Response.Redirect, Response.End or Server.Transfer functions are used.
The ThreadAbortException is not at all an exception to worry and hence it must be ignored in the Catch block.
Solutions
There are two ways to ignore the ThreadAbortException inside the Try Catch Finally block
1. Using two Catch blocks
C#
try
{
Response.Redirect("https://www.aspsnippets.com");
}
catch(System.Threading.ThreadAbortException ex)
{
//Keep blank.
}
catch(Exception ex)
{
//Error Logging code.
}
finally
{
}
VB.Net
Try
Response.Redirect("https://www.aspsnippets.com")
Catch ex As System.Threading.ThreadAbortException
'Keep blank.
Catch ex As Exception
'Error Logging code.
Finally
End Try
Screenshot
2. Using IF statement inside Catch block
C#
try
{
Response.Redirect("https://www.aspsnippets.com");
}
catch (Exception ex)
{
if (!(ex is System.Threading.ThreadAbortException))
{
//Error Logging code.
}
}
finally
{
}
VB.Net
Try
Response.Redirect("https://www.aspsnippets.com")
Catch ex As Exception
If Not (TypeOf ex Is System.Threading.ThreadAbortException) Then
'Error Logging code.
End If
Finally
End Try
Screenshot