I have this code:
con = new iDB2Connection(connectString);
try { con.Open(); }
catch (iDB2ConnectionTimeoutException ex)
{ Console.WriteLine(ex.Message); }
catch (iDB2DCFunctionErrorException ex)
{ Console.WriteLine(ex.Message); }
catch (AccessViolationException ex)
{ Console.WriteLine(ex.Message); }
Close connection
if (con != null)
{
try
{
Console.WriteLine("CRASH IS AFTER THIS");
if (con.State != ConnectionState.Closed)
{
con.Close();
}
}
catch (iDB2ConnectionTimeoutException ex)
{
Console.WriteLine(ex.Message);
}
catch (iDB2DCFunctionErrorException ex)
{
Console.WriteLine(ex.Message);
}
catch (AccessViolationException ex)
{
Console.WriteLine(ex.Message);
}
catch (iDB2Exception ex)
{
Console.WriteLine(ex.Message);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
}
}
But I still get this nasty message when the Close connection is being run:
Unhandled Exception: IBM.Data.DB2.iSeries.iDB2DCFunctionErrorException: An unexp
ected exception occurred. Type: System.AccessViolationException, Message: Attem
pted to read or write protected memory. This is often an indication that other m
emory is corrupt.. ---> System.AccessViolationException: Attempted to read or wr
ite protected memory. This is often an indication that other memory is corrupt.
at IBM.Data.DB2.iSeries.CwbDc.DcDnIsAlive(Int32 functionNumber, IntPtr connec
tionHandle, IntPtr nullParm)
at IBM.Data.DB2.iSeries.MPConnection.IsAlive()
--- End of inner exception stack trace ---
at IBM.Data.DB2.iSeries.MPConnection.IsAlive()
at IBM.Data.DB2.iSeries.MPConnectionManager.GetConnection(iDB2Connection piDB
2Connection)
at IBM.Data.DB2.iSeries.iDB2Connection.Open()
I get this when I know the iSeries is down for maintenance.
How do I handle this so that the C# console application continues on?
Why don't you put it in the Finally block and use only one try/catch?
con = new iDB2Connection(connectString);
try
{
con.Open();
}
catch (iDB2ConnectionTimeoutException ex)
{
Console.WriteLine(ex.Message);
}
catch (iDB2DCFunctionErrorException ex)
{
Console.WriteLine(ex.Message);
}
catch (AccessViolationException ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (con != null && con.State == ConnectionState.Open)
con.Close();
}
Related
In my API, I have over 25 API controllers, in every controller, using the following code to catch exception, I think it is too many code here, any good suggestion for the structure, thanks.
try
{
*code here*
}
catch (UnauthorizedAccessException ex)
{
}
catch (BadRequestException ex)
{
}
catch (HttpRequestException ex)
{
}
catch (TimeoutRejectedException ex)
{
}
catch (FileNotFoundException ex)
{
}
catch (SqlException ex)
{
}
catch (ValidationException ex)
{
}
catch (Exception ex)
{
}
Any simple way to do that.
IF
you plan to handle each exception separately - your approach is the way to go. I suggest to use this "ugly" code simply because it is more readable. If all your exceptions have common handling (for example logging) - you can use only catch (Exception e) and call your logging methods. This will work for all types of exceptions.
OR
If you decide that some of your exceptions might have common handling - you can go with:
try
{
// do
}
catch (Exception e)
{
if (e is BadRequestException ||
e is HttpRequestException ||
e is TimeoutRejectedException )
{
// Log exception
}
}
OR
A good approach is to use a delegate for exception handling. Since you're going to log exceptions, the delegate will handle this.
Action<Exception> HandleError = (e) => {
// Log exception
};
catch (UnauthorizedAccessException e) { HandleError(e); }
catch (BadRequestException e) { HandleError(e); }
catch (HttpRequestException e) { HandleError(e); }
OR
You can combine the first and the second approach
if (e is BadRequestException ||
e is HttpRequestException ||
e is TimeoutRejectedException )
{
HandleError(e);
}
I'm trying to catch a duplicate key violation. I can see the System.OleDB.OleDBException in the Intellisense pop up, but the inner exception is null. How do I access the Error Code in the System.OleDB.OleDBException?
Greg
try
{
MyData.ConExec(sSQL);
}
catch (Exception ex)
{
OleDbException innerException = ex.InnerException as OleDbException;
if (innerException.ErrorCode == -2147217873)
{
// handle exception here..
}
else
{
throw;
}
}
don't declare an instance of the exception. It will surely return empty if you do.
try
{
MyData.ConExec(sSQL);
}
catch (OleDbException ex)
{
// handle excpetion here...
if (ex.ErrorCode == -2147217873)
{
}
}
catch (Exception e)
{
// if other exception will occur
}
In my method that writes to a database, I handle errors as shown in the code below. In catch (DbUpdateException ex) I want to re-throw the exception and catch it in the last catch (Exception ex).
Is that possible and how to do that? Code below doesn't do that.
using (Entities context = new Entities())
{
try
{
context.Office.Add(office);
retVal = context.SaveChanges();
}
catch (DbUpdateException ex)
{
SqlException innerException = ex.GetBaseException() as SqlException;
if (innerException != null && innerException.Number == (int)SQLErrorCode.DUPLICATE_UNIQUE_CONSTRAINT)
{
throw
new Exception("Error ocurred");
}
//This is momenty where exception is thrown.
else
{
throw ex;
}
}
catch (Exception ex)
{
throw
new Exception("Error");
}
}
The following would be better:
context.Office.Add(office);
retVal = context.SaveChanges();
Let the except bubble up. No need to catch stuff if all you are going to do is re-throw.
Note: throw ex; will reset the stack trace - you want to do throw; normally.
If you want to catch exceptions from other catches then they cannot be on the same level.
Your current code has this structure:
try
{
}
catch (...)
{
}
catch (...)
{
}
You need to change it to:
try
{
try
{
}
catch (...)
{
// throw X
}
}
catch (...)
{
// catch X here
}
But you should think very carefully if you really want/need this. It does not look like a productive error handling pattern.
And see this answer for the 4 different ways to (re)throw an exception and their consequences.
have you tried try nesting your try...catch blocks?
using (Entities context = new Entities())
{
try
{
try
{
context.Office.Add(office);
retVal = context.SaveChanges();
}
catch (DbUpdateException ex)
{
SqlException innerException = ex.GetBaseException() as SqlException;
if (innerException != null && innerException.Number == (int)SQLErrorCode.DUPLICATE_UNIQUE_CONSTRAINT)
{
throw new Exception("Error ocurred");
}
//This is momenty where exception is thrown.
else
{
throw ex;
}
}
}
catch (Exception ex)
{
throw new Exception("Error");
}
}
A try-catch processes only one catch block and they are evaluated in order. Therefore, if you really need this functionality you'll need to put a try-catch inside of a try-catch, like this:
using (Entities context = new Entities())
{
try
{
try
{
context.Office.Add(office);
retVal = context.SaveChanges();
}
catch (DbUpdateException ex)
{
SqlException innerException = ex.GetBaseException() as SqlException;
if (innerException != null && innerException.Number == (int)SQLErrorCode.DUPLICATE_UNIQUE_CONSTRAINT)
{
throw
new Exception("Error ocurred");
}
//This is momenty where exception is thrown.
else
{
throw ex;
}
}
}
catch (Exception ex)
{
throw
new Exception("Error");
}
}
Try this:
void YourMethod()
{
using (Entities context = new Entities())
{
try
{
context.Office.Add(office);
retVal = context.SaveChanges();
}
catch (DbUpdateException ex)
{
SqlException innerException = ex.GetBaseException() as SqlException;
if (innerException != null && innerException.Number == (int)SQLErrorCode.DUPLICATE_UNIQUE_CONSTRAINT)
{
throw
new Exception("Error ocurred");
}
//This is momenty where exception is thrown.
else
{
throw ex;
}
}
}
}
Then when you call your method enclose it with try catch block
try
{
YourMethod()
}
catch (Exception ex)
{
throw
new Exception("Error");
}
When you plan to nest your try-catch-block as described by "paul" be aware of the exception type:
using (Entities context = new Entities())
{
try
{
try
{
context.Office.Add(office);
retVal = context.SaveChanges();
}
catch (DbUpdateException ex)
{
SqlException innerException = ex.GetBaseException() as SqlException;
if (innerException != null && innerException.Number == (int)SQLErrorCode.DUPLICATE_UNIQUE_CONSTRAINT)
{
// this exception will be catched too in outer try-catch block <--------
throw new Exception("Error ocurred");
}
//This is momenty where exception is thrown.
else
{
throw ex;
}
}
}
// Catch (DbUpdateException ex) if you plan to have the rethrown exception to be catched <------------
catch (Exception ex)
{
throw new Exception("Error");
}
}
My code looks like this:
public bool myQuery(string cmd)
{
try
{
OracleCommand command = null;
command = new OracleCommand(cmd, sqlConnection);
command.ExecuteReader();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "error!");
return false;
}
return true;
}
My issue is when error ORA-02291 occurs in Oracle, its Exception is not caught. No error is shown, how do I catch this error ?
Check this:
if (ex.InnerException != null)
{
MessageBox.Show(ex.InnerException.Message, "error!");
}
catch (System.Data.OracleClient.OracleException ex)
{
int code = ex.Code;
// or
string eCode = ex.ErrroCode;
return false;
}
return true;
This question already has answers here:
Catch multiple exceptions at once?
(29 answers)
Closed 9 years ago.
I want to merge the catch blocks in the following code for code reuse reasons:
try
{
DoSomeInputOutput();
}
catch (InvalidOperationException ex)
{
HandleKnownException1(ex);
}
catch (InvalidDataException ex)
{
HandleKnownException1(ex);
}
catch (ArgumentNullException ex)
{
HandleKnownException1(ex);
}
catch (ArgumentOutOfRangeException ex)
{
HandleKnownException2(ex);
}
catch (ArithmeticException ex)
{
HandleKnownException2(ex);
}
catch (InvalidCastException ex)
{
HandleKnownException2(ex);
}
catch (Exception ex)
{
HandleUnknownException(ex);
}
to something like this:
try
{
DoSomeInputOutput();
}
catch (InvalidOperationException ex)
catch (InvalidDataException ex)
catch (ArgumentNullException ex)
{
HandleKnownException1(ex);
}
catch (ArgumentOutOfRangeException ex)
catch (ArithmeticException ex)
catch (InvalidCastException ex)
{
HandleKnownException2(ex);
}
catch (Exception ex)
{
HandleUnknownException(ex);
}
Is that possible somehow?
Thanks.
Presumably, you do it in more than one place. If so, why don't you do this:
{
DoSomeInputOutput();
}
catch (Exception ex)
{
HandleInputException(ex);
}
void HandleInputException(Exception ex)
{
if (ex is InvalidOperationException || ex is InvalidDataException || ex is ArgumentNullException)
{
HandleKnownException1 (ex);
}
else if ...
else if ...
}
No (or at least: not unless the exceptions you want to group happen to share a common base-class specific to that group, which they don't in your example); the only thing you can do in this scenario is catch (Exception ex) and do runtime testing on ex. By the time you've done that, I expect your code is already "prettier" as-is (since, importantly, you've already refactored the handling code into a method).
I'd be tempted to tweak the spacing so I can focus on the important code:
try
{
DoSomeInputOutput();
}
// blah humorous scenario 1
catch (InvalidOperationException ex) { HandleKnownException1(ex); }
catch (InvalidDataException ex) { HandleKnownException1(ex); }
catch (ArgumentNullException ex) { HandleKnownException1(ex); }
// blah whimsical scenario 2
catch (ArgumentOutOfRangeException ex) { HandleKnownException2(ex); }
catch (ArithmeticException ex) { HandleKnownException2(ex); }
catch (InvalidCastException ex) { HandleKnownException2(ex); }
// unexpected comedy
catch (Exception ex) { HandleUnknownException(ex); }
(or something).
In some ways this also ties into this question: switch / pattern matching idea.
You could only do something like this if you had a decent hierarchy of exceptions, then you could catch a an exception of a type higher up in the hierarchy. However, exception hierarchies are meant to be pretty shallow by design and there is no guarantee that you would want to handle the exceptions the same way based solely on the hierarchy. And besides... none of that would help with standard exception types used in your example.