C# fails to catch error in opening a database connection? - c#

I have written a function in my windows forms application that will return true or false based on the success in opening a connection to a database however my try catch block fails to catch the exception that is thrown.
private bool TestConnect()
{
try
{
conn.Open();
return true;
}
catch (OleDbException e) { return false; }
}
Error thrown:
System.Data.OleDb.OleDbException
Please help, I can not for the life of me figure this one out!

I figured it out, I needed to alert VS that I wanted to Except this error

Related

Function ...Workbooks.Open() is failed while opening .xla and .xla addins of excel through c# - HRESULT: 0x80010105 (RPC_E_SERVERFAULT)

I wrote a code in c# in Visual studio and I open excels, run macro and close the excel
I do it in cycles (in a loop and delay between every cycle)
sometimes the function failes and sometimes it works
The error message I got:
"The server threw an exception. (Exception from HRESULT: 0x80010105 (RPC_E_SERVERFAULT))"
Please can someone help me ???
public void Open()
{
try
{
ExcelApp.Workbooks.Open(#"C:\Program Files (x86)\REFPROP\REFPROP.XLA");
ExcelApp.Workbooks.Open(#"C:\Program Files (x86)\REFPROP\REFPROP_Ribbon.xlam");
foreach (Excel.AddIn item in ExcelApp.AddIns)
{
if (item.Name.Equals("REFPROP.XLA") || item.Name.Equals("REFPROP_Ribbon.xlam"))
{
item.Installed = false;
item.Installed = true;
}
}
Thread.Sleep(3000);
//so then opening excel workbooks:
ExcelBook = ExcelApp.Workbooks.Open(ExcelPath);
Opened = true;
Thread.Sleep(3000);
ExcelApp.Workbooks.Open(#"C:\Program Files (x86)\REFPROP\REFPROP.XLA");
ExcelApp.Workbooks.Open(#"C:\Program Files (x86)\REFPROP\REFPROP_Ribbon.xlam");
foreach (Excel.AddIn item in ExcelApp.AddIns)
{
if (item.Name.Equals("REFPROP.XLA") || item.Name.Equals("REFPROP_Ribbon.xlam"))
{
item.Installed = false;
item.Installed = true;
}
}
Thread.Sleep(3000);
}
catch (Exception e)
{
throw;
}
}
There can be multiple reasons why you are getting that exception at runtime.
First, I'd suggest releasing underlying COM objects in the code and do not rely on the GC. Use the Marshal.ReleaseComObject method for that and then set the object to null.
Second, try to set the calculation mode to manual.
Third, make sure that the file doesn't require admin privileges.
You may find a similar thread helpful, see Excel interop The server threw an exception. (Exception from HRESULT: 0x80010105 (RPC_E_SERVERFAULT)).

How to differ from writing exception to a reading one?

I have a socket and I'd like to send messages and read from it.
When I read/write with the socket while the other side is offline, I get the same Exception: System.IO.IOException: Unable to read data from the transport connection: Operation on non-blocking socket would block.
How can I identify in which of the two it happened besides having two separate try-catch blocks? Can't I just get a Timeout Exception when the reading timeout is over?
example:
try
{
SendData("!GetLocation!");
string data = GetData();
}
catch (Exception ex)
{
if (ex is System.IO.IOException)
{
//How can I identify if the exception was raised at the read method or the write method?
}
}
Yeah, exception handling is heavy resource wise, but sometimes is not so bad.
If you stick to only one try-catch you can check the error message.
Note: I have also added a second try-catch for generic (non IO) errors
try
{
SendData("!GetLocation!");
string data = GetData();
}
catch (System.IO.IOException ex)
{
if (ex.Message.IndexOf("Unable to read") != -1)
{
// GetData error
}
else if (ex.Message.IndexOf("Unable to write") != -1)
{
// SendData error
}
else
{
//Other IO errors
}
}
catch(Exception exc)
{
// Unspected errors
}
you could also set a boolean variable and check its value to know where it
broke your code.
bool sendCalled = false;
try
{
SendData("!GetLocation!");
sendCalled = true;
string data = GetData();
}
catch (System.IO.IOException ex)
{
if (sendCalled)
{
// GetData error
}
else
{
// SendData error
}
}
Not that I endorse either of these solutions, but an answer is an answer: you can either
analyze the stack trace of the exception to find out which call failed (e.g. name of the method at the top of the stack frame
set a flag after the write, and do logic based on that flag
Neither of these is as straight forward as wrapping each method call. In fact, wrapping each call conveys your intent. In the catch of your first call, you can return/break/skip the read call, which explicitly tells the reader you're bailing out fast.

Try inside catch to ensure finally executes

I have to process items off a queue.
Deleting items off the queue is a manual call to Queue.DeleteMessage. This needs to occurs regardless of whether or not the processing succeeds.
var queueMessage = Queue.GetMessage();
try
{
pipeline.Process(queueMessage);
}
catch (Exception ex)
{
try
{
Logger.LogException(ex);
}
catch { }
}
finally
{
Queue.DeleteMessage(queueMessage);
}
Problem:
On failure, I log the error to some data store. If this logging fails (perhaps the data store is not available), I still need the message to be deleted from the queue.
I have wrapped the LogException call in another try catch. Is this the correct way or performing thing?
Following code is enough. finally blocks execute even when exception is thrown in catch block.
var queueMessage = Queue.GetMessage();
try
{
pipeline.Process(queueMessage);
}
catch (Exception ex)
{
Logger.LogException(ex);
}
finally
{
Queue.DeleteMessage(queueMessage);//Will be executed for sure*
}
The finally block always executes, even if it throws an unhandled error (unless it end the app). So yes.

Handling Error "WebDev.WebServer.Exe has stopped working"

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.

Getting Error: "underlying connection closed: unexpected error on request receive"

I am using .Net application with web service(.net) and oracle database. But when i send some request to the server and waiting for the result it is giving following error
The underlying connection was closed: An unexpected error occurred
I am unable to get the cause of the error. Can any one plese help me to get actual cause of this error and what i need to do solution. This errror occurce only in Production Server. Same code in Dev and Test server it is working.
This is probably caused by the error inside web service method or function that you are calling. Just create proper error handling and log web service exception. Here is my sample code:
[WebMethod]
public void MyServerMethod()
{
try
{
//open connection and execute your calls to Oracle DB...
}
catch (Exception ex)
{
LogServiceException(ex);
throw ex;
}
}
void LogServiceException(Exception ex)
{
string fullMessage = ex.Message;
while (ex.InnerException != null)
{
ex = ex.InnerException;
fullMessage += " Inner exception: " + ex.Message;
}
//log your exception to log file, DB or eventlog...
//in this case I will use log file, just make sure you appropriate filesystem rights to do this...
System.IO.File.AppendAllText("LogFile.txt", fullMessage);
}

Categories