.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

why doesn't this catch block get reached?

Posted By:      Posted Date: September 14, 2010    Points: 0   Category :ASP.Net
I have code for sending an email.  I set a value in my config file for that would throw an smtpfailedrecipient exception.  This exception is being thrown but it isn't reaching the catch block.I get an smtpfailedrecipientexception that is at the send method in the try block.  The error says that the "exception was unhandled by user code".  I don't understand why the catch block isn't being reached.  I thought this would be reached in this situation.  I thought this is what the catch block was for.Can someone please help me understand how to design this better or why this isn't working the way I thought it would? try { client.Send(message); <-- this throws the exception } catch (SmtpFailedRecipientsException ex) { #region Catch logic for (int i = 0; i < ex.InnerExceptions.Length; i++) { SmtpStatusCode status = ex.InnerExceptions[i].StatusCode; if (status == SmtpStatusCode.MailboxBusy || status == SmtpStatusCode.MailboxUnavailable) { lblMessage.Visible = true; lblMessage.Text = "Deli

View Complete Post

More Related Resource Links

Catch Block question

What are the scenarios in which a t-sql catch block will not be called?   I have a SP which does partition management, sometimes i see that partitions have not been properly created... but still the catch block was never called. This is getting very hard to debug.   Can it be that in some timeout scenarios the catch block is not called?

try catch block

Hi Guys, I have a very simple question. whether to put the select stmt in try/catch or not? Its advantage,disadvantage if any will be of great help.~Technology Analyst~

Try-Catch block cannot handle exceptions when contacting a Silverlight Client using net.tcp Duplex W

I have created a simple duplex WCF for Silverlight 4 clients, using net.tcp binding (.NET Framework 4.0)  The client interface is declared as <ServiceContract()> _ Public Interface IServiceClient <OperationContract(IsOneWay:=True)> _ Sub SendUpdate(ByVal allRecords As List(Of String)) End Interface while the service interface is declared as <ServiceContract(Namespace:="SilverlightService", CallbackContract:=GetType(IServiceClient))> _ Public Interface IService <OperationContract(IsOneWay:=True)> _ Sub Connect() End Interface The service code is implemented like: <ServiceBehavior(ConcurrencyMode:=ConcurrencyMode.Multiple, InstanceContextMode:=InstanceContextMode.Single)> _ <Activation.AspNetCompatibilityRequirementsAttribute(RequirementsMode:=Activation.AspNetCompatibilityRequirementsMode.Allowed)> _ Public Class Service Implements IService 'Keep the list of all the active/connected clients: Public _clients As List(Of IServiceClient) = New List(Of ITrackServiceClient) Public Sub Connect() Implements IService.Connect Dim client = OperationContext.Current.GetCallbackChannel(Of IServiceClient)() Dim clientExist = From p In _clients _ Where p Is client _ Select p If clientExist.Count() = 0 Then Monitor.Enter(_clients) _clients.Add(client) Monitor.E

Try Catch block is not work that try block failed but catch block is not excuted


I am facing the problem: Try Catch block is not work that try block failed but catch block is not excuted.

In my case, I tried to excuted the sql like below:

begin try

update [table] set [column] = abc

end try

begin catch
 select 'catch error'
end catch


The [column] is numeric format, but data set to it is not valid number.

When excute this sql, the following error prompt out:

Invalid column name 'abc'.

And the catch block has not been excuted.


I want to know what happen in this case.

Moreover, I found an article talks about the similar case too:



Is there any solution so that I can catch the error without stopping the batch?

Thanks a lot.

dm_fts_parser inside try-catch block


Hi, I'm working on a project and have a code similar to the code posted below and I would like to understand why the CATCH block is never executed. If the try catch is removed the dm_fts_parser will send an error complaining search string syntax, however inside a try-catch block the code will silently return an empty recordset, no error is triggered and catch block is never executed.


USE master

      @StopWordListID int 
      , @SearchString varchar(1000) 
      , @WordBreakerLcid int 
      , @AccentSensitivity bit

      @SearchString = '"Introduction" OR "Repair and Service'
      , @WordBreakerLcid = 1033 -- English word breaker 
      , @AccentSensitivity = 0 -- Default is not accent sensitive

      @StopWordListID = ft.stoplist_id 
FROM    AdventureWorks2008.sys.tables t 
      INNER JOIN AdventureWorks2008.sys.fulltext_indexes ft ON ( t.object_id = ft.object_id ) 
WHERE   ( t.name = 'Document' )

        , LEFT ( dfp.special_term , 200 ) 
    FROM  AdventureWorks2008.sys.dm_fts_parser ( @SearchString , @WordBreakerLcid , @StopWordListID , @AccentSensitivity ) dfp
    PRINT 'Ok'
    PRINT 'Error'


WPF XBAP Release Doesn't Throw/Catch Errors


On my development box, launching the XBAP in either Debug or Release with Visual Studio 2010... it throws and catches errors just fine.  So I published the app to be hosted on our Win2008 R2 server...  Now here is what is wierd.  On my machine, hitting the published app still throws/catches errors just fine.  But on other users workstations, it just locks up IE for them, no error, no eventvwr message, nothing.

Any ideas?

Thanks a lot!!!



In App.xaml.cs I am catching all unhandled exceptions this way:

  public partial class App : Application
    protected override void OnStartup(StartupEventArgs e)
      Application.Current.DispatcherUnhandledException += AppDispatcherUnhandledException;
    protected void AppDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
      e.Handled = true;
    protected static void HandleException(Exception ex)
      ErrorWindow errorWindow = new ErrorWindow("Error connecting to servers, please try reloading the page!", ex, false);

Getting Exception info from catch block to Application_Error event of HttpModule


I need some help regarding one issue I am facing. I created a httpmodule for hadling the unhandled errors and I need to log those errors using log 4 net in database.

Everting working fine but I am not getting any error information once the error was hadled and I need that info too. I want to make it as a centralize module which can trap all errors and log those errors.

How call application_error event of httpmodule from catch block...so that I can log that info there and I no need log in every catch block..


How to Add a Send Activity in a Workflow Service try/catch catch block?


For a Workflow Service that has ReceiveRequest/SendResponse Activities, you can right click on the ReceiveRequest Activity a do a Create SendReply to add multiple SendResponse Activities. 

The problem is that I want to have a Try/Catch block in the Workflow Service.  This way when a fault occurs, I want to log the exception in my database and then use a Send or a SendResponse Activity to send the fault information back to the caller of the workflow service.

Bottom line is that VS2010 does not allow me to add an additional SendReply Activity inside the catch block.

Do you know how to do this?


Leo Cono, http://www.YouLoveMe.com - Free Dating


Why is Thread.Sleep() not interruped when it is in catch block?


Take a look at following simple code..
(This program is not meant to do some useful things. It's just for a demonstration purpose.)

class Program {
    private static void Main(string[] args) {
        // start new thread.
        Thread thread = new Thread(new ThreadStart(ThreadFunc));
        thread.IsBackground = false;

        // interrupt the thread.

    private static void ThreadFunc() {
        try {
            try {
                // assume something goes wrong...
                throw new Exception("TEST");
            catch (Exception) {

MVC architecture in ASP.Net using C# and Microsoft Data Access Application block

The Model-View-Controller (MVC) pattern separates the modeling of the domain, the presentation, and the actions based on user input into three separate classes [Burbeck92]:

Model. The model manages the behavior and data of the application domain, responds to requests for information about its state (usually from the view), and responds to instructions to change state (usually from the controller).

View. The view manages the display of information.

Controller. The controller interprets the mouse and keyboard inputs from the user, informing the model and/or the view to change as appropriate.

SQL Server 2005 Try and Catch Exception Handling

I'm pretty excited to see that there is some real error handling for T-SQL code in SQL Server 2005. It's pretty painful to have your wonderfully architected .NET solution tainted by less-than-VBScript error handling for stored procedures in the database. The big difference being the addition of TRY..CATCH blocks. Let's take a look:

Beginner: this doesn't make sense to me


Do you need and "empty" script tag in the head to run scripts that are in the body?  Also, can you run JQuery scripts if they're in the <head> tag?  The first sample only works if the JQuery script is in the form (and body) tag, not in the head - even if I add $(document).ready(function() { });

This works

<head runat="server">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" />
<script type="text/javascript">
<form id="form1" runat="server">
<a href="">Here is a link</a>
<script type="text/javascript">
$('a').click(function () {
alert("you clicked me!");


This doesn't work.  Notice I removed the second <script> tag from the head

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="serve

reader.getordinal("column_may_not_exist") how to catch the exception?



would any body please help me to catch the exception if the column doesnot exist as my table columns are not static.

sometimes its throwing me indexoutofrange exception as the column doesnot exist

thanks for the help guys

Error while using exception handling block el 4.1


Hi Folks,


i am trying to use tyhe exception handling block of Enterprise library 4.1.


I just createda polisy and used IndexOutOfRangeException and added a replace handler and a logging handler to it.

I am using the NotifyRethrow PostHandlingAction to the exception.


During runtime I am getting an exception on the HandleException event, The exception is added below:



Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 42:             catch (Exception ex)
Line 43:             {
Line 44:                 bool reThrow = ExceptionPolicy.HandleException(ex, "ReplacePolicy");
Line 45:         

Using the ConsoleTraceListener with the Enterprise Library 3.1 Logging Block


I'm new to using the Logging application block.  I think I have a pretty good handle on how things work.  However, I'm running into a problem.  I'm using the RollingFlatFileListener and I have formatted the logging template to be more like the logging we are replacing.  However, in our console apps when the ConsoleTraceListener is added it still logs it out in the default text template format.  Is there any way to get around this?  Currently it looks like I will have to create a new TraceListener called FormattedConsoleListener that allows a text formatter to be associated with it.  Is this the only way?

set messageTemplateResourceName from resource file in Validation appication block.



  I am using Validation application block in my project and want to set validation message from resource file, but not able to do that. I tried giving the path of resource file in messageTemplateResourceType and name of resource in messageTemplateResourceName. But it did not help as I only receive the message if I have set something in messageTemplate even after setting the resource file.

Here is my code:

<validator lowerBound="1" lowerBoundType="Inclusive" upperBound="250"
              upperBoundType="Inclusive" negated="false" messageTemplate=""
              messageTemplateResourceType="Asurion.jCare.Common.Resources.UIResources.PerilTypeAndDetailsSection, Asurion.jCare.Common.Resources, Version=, Culture=neutral, PublicKeyToken=null"
              tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.StringLengthValidator, Microsoft.Practices.Enterpris

Microsoft Application Block for Data Access in .NET


Hi all,

I was rummaging the internet learning aspx and came across the concept of: Microsoft Application Block for Data Access in .NET

It seems great of course. The articles are all early 2003-5 such as


So the question is - is this tech still relevant and should I be using it?



ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend