I thought that if I wrap the EndInvoke call with a try catch if an error is thrown then my catch block would handle it? I must being doing something wrong??? Has to be user error, just not sure what?
EDIT:
I get the "Exception was unhandled by user code" being thrown when I run this which is stopping the application. If I step through the code I see that and then it will go to the catch block. But, I would expect the catch block to handle this and not see the unhandled exception that is stopping the application?
Any suggestions appreciated.
class Program
{
static void Main(string[] args)
{
Action myMethod = new Action(Program.FooOneSecond);
Go("Go Method");
IAsyncResult tag =
myMethod.BeginInvoke(null, "passing some state");
try
{
myMethod.EndInvoke(tag);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
string strState = (string)tag.AsyncState;
Console.WriteLine("State When Calling EndInvoke: "
+ tag.AsyncState.ToString());
Console.Read();
}
static int Work(string s) { return s.Length; throw null; }
static void Go(string s)
{
Console.WriteLine(s);
}
static void FooOneSecond()
{
// sleep for one second!
Thread.Sleep(1000);
// throw an exception
throw new Exception("Exception from FooOneSecond");
}
}
I just ran your code and the exception gets caught every time...
Related
Hello guys i'm working on Database assignment in this i have one windows form and one class that i use to connect database and to execute queries and non-queries.
Question: I m using Post-Message label which inform only when "Product added successfully".but when i send wrong-data which can occur exception in executeNonQuery() in database class and after catching this exception and showing Error in message box.Control goes back to caller and it prints lblPostMsg in both cases which is "Product has been added successfully".
I want that when exception occur in database class i can stop executing rest of the code or if there is way that exception in calling method can be caught by caller method.
below is Code of windows Form button
private void btnInsert_Click(object sender, EventArgs e)
{
con = new DbConnection();
con.SqlQuery("INSERT INTO products VALUES(#products_ID,#products_Name)");
con.cmd.Parameters.AddWithValue("#products_ID", txtProID.Text);
con.cmd.Parameters.AddWithValue("#products_Name", txtProName.Text);
try
{
con.ExecuteNonQueryF();
this.categoriesTableAdapter1.Fill(this.purchasemasterDS.categories);
SystemSounds.Beep.Play();
lblPostMsg.Show();
lblPostMsg.Text = "Product has been added successfully";
}
catch (Exception ex)
{
throw;
}
finally
{
con.CloseCon();
}
}
This code is from dbclass
public void ExecuteNonQueryF()
{
try
{
_con.Open();
cmd.ExecuteNonQuery();
}
catch (System.Exception ex)
{
MessageBox.Show("Exception " + ex);
}
you are catching, handling, and suppressing the Exception in ExecuteNonQueryF:
catch (System.Exception ex)
{
MessageBox.Show("Exception " + ex);
}
Though this handles the Exception by showing the message, it causes the code to continue executing; the Exception won't be raised to the caller.
If you add throw after your MessageBox.Show is executed, the Exception will be raised to the caller and execution stops.
catch (System.Exception ex)
{
MessageBox.Show("Exception " + ex);
throw;
}
Another option is to completely remove that try-catch in ExecuteNonQueryF - letting the caller (your button onclick method) handle the Exception.
you need to throw an explicit exception in ExecuteNonQuery's catch block like
throw new Exception(ex)
and then in calle's catch block you need to write "return" to return from function. This will stop furter execution of function.
If you want the Exception will be raised to the caller and execution stops, then you must use throw at the last line of your catch block.
catch (System.Exception ex)
{
/*
write your desire code. then throw
*/
throw;
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 4 years ago.
Improve this question
I am bit confused regarding the finally block. I know that finally block gets executed no matter if there is an exception or not.
I have got 2 scenarios :-
1) If there is an exception in try block and I have not written any catch block for this try block, but I have a finally block, then will the finally block gets executed? Does finally block executed if the exception is unhandled?
Below is an example code :-
static void Main(string[] args)
{
int x = 0;
try
{
int divide = 12 / x;
}
//catch (Exception ex)
//{
// int divide = 12 / x;
// Console.WriteLine(ex.Message);
//}
finally
{
Console.WriteLine("I am finally block");
}
Console.ReadLine();
}
2) Will the finally block get executed if there is an exception in catch block?
Below is the sample code :-
static void Main(string[] args)
{
int x = 0;
try
{
int divide = 12 / x;
}
catch (Exception ex)
{
int divide = 12 / x; // this will throw exception in catch block
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("I am finally block");
}
Console.ReadLine();
}
I have tried these codes and I don't see the finally block getting executed.
Please explain me why the finally block is not executed.
In really simple terms, these are what try-catch-finally blocks do:
Try
The place where you'd put potentially problematic code. If an exception is generated, an exception will be thrown.
Catch
Catch is the ONLY block where an exception will be caught. Hence the name. So when an exception is thrown, if you want to ensure the program doesn't 'hang', you must catch the exception.
Finally
Do your cleanup. If, say, you have some array in your try block and you want to clean it up in case of an exception, this is the place to do it.
Try-Finally
The documentation says:
Within a handled exception, the associated finally block is guaranteed to be run. However, if the exception is unhandled, execution of the finally block is dependent on how the exception unwind operation is triggered. That, in turn, is dependent on how your computer is set up.
Meaning, if you don't catch your exception, it depends on the situation whether finally is run.
So, with that in mind, let's look at your first code block.
static void Main(string[] args)
{
int x = 0;
try
{
int divide = 12 / x;
}
finally
{
Console.WriteLine("I am finally block");
}
Console.ReadLine();
}
You're attempting to do a divide by zero which generates an exception. But there's no place for it to be 'caught', so the program hangs:
So if you add a catch block here, now it will allow for smooth sailing and go to your finally as well.
try
{
int divide = 12 / x;
}
catch (Exception ex)
{
Console.WriteLine("Oops. Division by Zero.");
}
finally
{
Console.WriteLine("I am finally block");
}
Now let's take your second code snippet. I'm going to do a small modification and flip the order of two lines of code inside the catch.
static void Main(string[] args)
{
int x = 0;
try
{
int divide = 12 / x;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
int divide = 12 / x;
}
finally
{
Console.WriteLine("I am finally block");
}
Console.ReadLine();
}
Now, the catch block catches the exception thrown by the first illegal division and prints a message. But then there's a second illegal division inside the catch, and there's no catch for that thrown exception so the program hangs.
So if you modify it to have a second try-catch inside the first catch like so:
static void Main(string[] args)
{
int x = 0;
try
{
int divide = 12 / x;
}
catch (Exception ex)
{
try
{
Console.WriteLine(ex.Message);
int divide = 12 / x;
}
catch (Exception ex2)
{
Console.WriteLine(ex2.Message);
}
}
finally
{
Console.WriteLine("I am finally block");
}
Console.ReadLine();
}
Now it will catch both exceptions and you're good to go.
So the idea is, if you have a try you should try to have a catch unless you can justify why you don't want one.
Following the article MSDN
Within a handled exception, the associated finally block is guaranteed
to be run
That means for try catch finally, the code in finally must be executed.
int x = 0;
try
{
int divide = 12 / x;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("I am finally block");
}
Console.ReadLine();
With the output:
Attempted to divide by zero. // catch Console.WriteLine(ex.Message);
I am finally block // finally
If the exception is unhandled, execution of the finally block is
dependent on how the exception unwind operation is triggered. That, in
turn, is dependent on how your computer is set up.
That means it depends the exception thrown finally code will be executed or not. If StackOverflowException or an exception i.e ExecutionEngineException, which may invoke to call Environment.FailFast() or Environment.Exit(), your finally code won't be executed because your application has closed before.
In your case 2, there is an exception DivideByZeroException in catch or in try in the case 1 , the code finally in this case will be executed.
int x = 0;
try
{
int divide = 12 / x;
}
catch (Exception ex)
{
int divide = 12 / x; // no handled
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("I am finally block");
}
Console.ReadLine();
The output:
I am finally block // finally
Run-time exception (line 16): Attempted to divide by zero. // exception non handled catch by the level plus high that cause crashing the application
I have a service manager that checks and controls services that are connected to it. But sometimes one of my service is getting crushed and service manager can't know whether it is still working or not. (Because of the dialog box which shows debug and close options). So i found an accepted solution that catches unhandled exceptions, but doesn't work in my code.
Here is my code that doesn't catch unhandled exceptions.
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(unhandled_exceptions);
new Thread(() =>
{
start()
}).Start();
}
public void unhandled_exceptions(object sender, UnhandledExceptionEventArgs e)
{
this.disconnect();
logger.Error(e);
logger.Info("Catched unhandled exception, that causes to crash application. Disconecting from service manager..");
Environment.Exit(1);
}
public override void start()
{
try
{
throw new ArgumentException("erer");
}
catch (Exception ex)
{
logger.Error(ex);
}
Thread.Sleep(5000);
PerformOverflow();
}
void PerformOverflow()
{
PerformOverflow();
}
.Net 4.6, Console applicaiton
I don't know what causes to crash my application, in actual fact the start method is in a try catch blog. I am using StackOverflowException because it is not unhandled too. I think If i catch it i could catch the real one that crashes my app.
Is there a way to handle the error "WebDev.WebServer.Exe has stopped working" in ASP.NET and keep the page running or even the just the WebServer running? Or is this an impossible task and is essentially like asking how to save someone's life after they've died?
I have the error-causing code inside a try/catch block, but that doesn't make a difference. I've also tried registering a new UnhandledExceptionEventHandler, but that didn't work either. My code is below in case I'm doing something wrong.
Also to be clear, I'm not asking for help on how to prevent the error; I want to know if and when the error happens if there's anything I can do to handle it.
UPDATE 1: TestOcx is a VB6 OCX that passes a reference of a string to a DLL written in Clarion.
UPDATE 2: As per #JDennis's answer, I should clarify that the catch(Exception ex) block is not being entered either. If I removed the call to the OCX from the try\catch block it still won't reach the UnhandledException method. There are essentially two areas that don't ever get executed.
UPDATE 3: From #AndrewLewis, I tried to also add a regular catch block to catch any non-CLS compliant exceptions, and this did not work either. However, I later found that since .NET 2.0 on, all non-CLS exceptions are wrapped inside RuntimeWrappedException so a catch (Exception) will catch non-CLS compliant exceptions too. Check out this other question here for more info.
public bool TestMethod()
{
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
string input = "test";
string result = "";
try
{
TestOcx myCom = new TestOcx();
result = myCom.PassString(ref input); // <== MAJOR ERROR!
// do stuff with result...
return true;
}
catch (Exception ex)
{
log.Add("Exception: " + ex.Message); // THIS NEVER GETS CALLED
return false;
}
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
// THIS NEVER GETS CALLED
try
{
Exception ex = (Exception)e.ExceptionObject;
log.Add("Exception: " + ex.Message);
}
catch (Exception exc)
{
log.Add("Fatal Non-UI Error: " + exc.Message);
}
}
You should try catching non-CLS compliant exceptions to make sure nothing is being thrown (keep in mind you don't want to do this in production, always be specific!):
try
{
TestOcx myCom = new TestOcx();
result = myCom.PassString(ref input); // <== MAJOR ERROR!
// do stuff with result...
return true;
}
catch (Exception ex)
{
log.Add("Exception: " + ex.Message); // THIS NEVER GETS CALLED
return false;
}
catch
{
//do something here
}
Your code reads //THIS NEVER GETS CALLED.
If you catch the exception it is no longer un-handled. this is why it doesn't fire an unhandledexception event.
I am writing an application in which when something happened to the connection I want to pop up a messagebox and show the user the error...
for this purpose when the program throw an exception it will come to the catch block and in that I want to show the user the message here is the code :
catch (WebException ex)
{
if (!(ex.Message == "The operation has timed out."))
{
MessageBox.Show(ex.Message);
}
}
As it seems the program will come to this catch something like forever till the connection is become fixed so what should I do to update my message on just one messagebox at a time?
There is not much control over MessageBox when it's displayed. I would use another Form displayed in a modal mode. Before displaying, you can start a separate thread and put the logic to monitor the connection. When re-established, notify the message form and close it.
You can use something like:
public static class FailureMessagebox
{
private static bool _hasBeenSuccessful = true;
public static void ShowIfFailure(Action someAction)
{
try
{
someAction();
_hasBeenSuccessful = false;
}
catch (Exception err)
{
if (_hasBeenSuccessful)
MessageBox.Show(ex.Message);
_hasBeenSuccessful = false;
throw;
}
}
}
Sample usage:
try
{
WebResponse response;
FailureMessagebox.ShowIfFailure(() => response = webRequest.GetResponse());
}
catch (WebException err)
{
//handle the exception here.
}