After executing this code:
try
{
DoSomething();
}
catch (TaskCanceledException e)
{
DealWithCancelledTaskException(e);
throw;
}
catch (Exception e)
{
DealWithNormalException(e);
throw;
}
The exception is raised.
DoSomething is supposed to throw TaskCancelledException, but it throws System.AggregateException containing one exception of type TaskCancelledException and is caught as normal Exception.
How can I catch this exception as TaskCancelledException?
It is most likely that your code is throwing an AggregateException
Firstly try explicitly catching AggregateException. Then to access the exception that has been wrapped up by the aggregate exception use the InnerException Property. You can also access the list of all exceptions that have been aggregated (if there is or could be more than 1) by accessing the InnerExceptions property which gives you a list of the exceptions that this exception has aggregated
Related
How to detect the InvalidOperationException type
Here is the inner exception message:
System.InvalidOperationException: ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.
I need to detect exactly this type of exceptions to handle it.
Can I know its HResult number or the exception code? or another way?
This code may help
try
{
//your code here...
}
catch (Exception exception) when (exception.InnerException is InvalidOperationException)
{
var exceptionMessage = "ExecuteNonQuery requires an open and available Connection";
if (exception.Message.Contains(exceptionMessage) || exception.InnerException.Message.Contains(exceptionMessage))
{
//handle it...
}
}
You can use a try/catch exception handling hierarchy, so that InvalidOperationException will be caught first and handled separately from other exception types such as the generic exception type.
try
{
// Normal workflow up here
}
catch (System.InvalidOperationException ioex)
{
// Handle InvalidOperationException
Console.WriteLine(ioex.StackTrace);
}
catch (System.Exception ex)
{
// Handle generic exception
Console.WriteLine(ex.StackTrace);
}
However, your question suggests that this will not work for you, because you mention an inner exception. In that case you probably need to do some type checking on the inner exception like this:
try
{
// Normal workflow up here
}
catch (System.Exception ex)
{
if (ex.InnerException is InvalidOperationException)
{
// Handle InvalidOperationException
}
else
{
// Handle generic exception
}
Console.WriteLine(ex.StackTrace);
}
Could you give us more context? It would make it easier for us to answer your question.
However, if I understand you correctly, you try to process 'something' with the inner exception. As of C# 6 there are exception filters available. For more information about exception filters see Exception filters.
The documentation also provides an example.
In your specific case, you could use the exception filter as follows:
try
{
// Do something that could cause a InvalidOperationException
}
catch (InvalidOperationException ex) when (ex.InnerException is SomeTypeOfException)
{
// Handle this type of exception
}
catch (InvalidOperationException ex) when (ex.InnerException is AnotherSomeTypeOfException)
{
// Handle this kind of exception
}
it is allowed to use custom exception, where the exception can be thrown like below.
try
{
int foo = int.Parse(token);
}
catch (FormatException ex)
{
//Assuming you added this constructor
throw new ParserException(
$"Failed to read {token} as number.",
FileName,
LineNumber,
ex);
}
But in a normal try catch block, it says , throwing exceptions will clear the stacktrace.
try
{
ForthCall();
}
catch (Exception ex)
{
throw ex;
}
So in custom exception,how it managed to use throw exception, without clear the stacktrace?
There are several ways this can be done.
As mentioned in this link In C#, how can I rethrow InnerException without losing stack trace?, you can use the ExceptionDispatchInfo Class
with code similar to
try
{
task.Wait();
}
catch(AggregateException ex)
{
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
}
Another way is to have your handler return a boolean, whether the exception was handled or not, so you can use this in your catch clause:
catch (Exception ex) {
if (!HandleException(ex)) {
throw;
}
}
where HandleException is your custom Exception handler. Gotten from this link: How to throw exception without resetting stack trace?
Whenever you use throw with an exception object, it fills in the stack trace at that point. (Compare to Java, which populates stack traces when an exception is constructed.)
If you use throw without an exception object, which you can only do in a catch clause, the caught exception object is re-throw without alteration.
I have created few custom exception class
public class CreateNewUserWebException : Exception
{
public CreateNewUserWebException(string email): base(
string.Format("[{0}] - User could not be added.", email))
{
}
}
public class CreateNewUserEntityFrameworkException : System.Data.DataException
{
public CreateNewUserEntityFrameworkException(string email)
: base(
string.Format("[{0}] - User could not be added.", email))
{
}
}
and here is my controller code
try
{
var user = _createUserModule.CreateUser(model);
CookieManager.SetAuthenticationCookie(user, model.Email, rememberMe: false);
return RedirectToAction("Index", "Bugs");
}
catch (CreateNewUserEntityFrameworkException exception)
{
this.ModelState.AddModelError("", "Some error occured while registering you on our sytem. Please try again later.");
Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
}
catch (CreateNewUserWebException exception)
{
this.ModelState.AddModelError("", "Some error occured while registering you on our sytem. Please try again later.");
Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
}
catch(Exception exception)
{
this.ModelState.AddModelError("", "Some error occured while registering you on our sytem. Please try again later.");
Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
}
I have purposely fully induced an primary key violation exception which is
but exception is not catched by my custom exception class. It is not caught by the last exception catch block.
I cannot understand why so. Can some one help me out on this please.
The part you've highlighted in the debugger is the inner exception. That isn't used by the CLR to determine which catch block to enter. The outer exception is just a DbUpdateException - which you haven't specified a particular catch block for.
Even the inner exception is just a DataException - it's not an instance of your custom exception.
You haven't shown any code which actually throws your exception - are you sure it's being used at all? What code have you written to tell EF to throw your exception rather than the exception it would otherwise throw?
(Given your comments, I'm not sure you quite understand exception handling. Creating a custom exception doesn't somehow let you catch an instance of that without it being thrown - something still has to throw an instance of that exception before it's any use.)
I am trying to log errors to a file but I can't seem to get the catch block to run when an error occurs. Here is an example of the code:
try
{
cmd.ExecuteNonQuery();
}
catch (MySQLException ex)
{
//run some logging code
}
finally
{
//clean up the resources
}
The problem is when there is an exception, I get the error thrown from the built in webserver that its an unhandled exception. When I debug the code stops at the exception then continues on to the finally block. Can someone point me in the right direction here?
ExecuteNonQuery() throws an exception of type SqlException.
So I'm not sure what MySQLException is, but you need to be catching an SqlException.
Look at this for extra info:
SqlCommand.ExecuteNonQuery Method
SqlException Class.
It seems like the exception thrown is not not of type MySQLException or any exception derived from it. So the catch block never never catches it and the finally block is executed directly!
To check what kind of exception was raised, modify the code to:
try
{
cmd.ExecuteNonQuery();
}
catch (MySQLException ex)
{
//run some logging code
}
catch (Exception ex)
{
// any other exception will be handled here
}
finally
{
//clean up the resources
}
That method can throw different types of exceptions
InvalidCastException
SqlException
IOException
InvalidOperationException
ObjectDisposedException
catch (OracleException e)
{
Cursor.Current = Cursors.Default;
_instance = null;
if (e.ErrorCode == -2147483648) // {"ORA-01017: invalid username/password; logon denied"}
{
throw new Exception("Nepravilno ime uporabnika ali geslo");
}
else
{
throw new Exception("Ne morem se povezati na podatkovno bazo. Preveri povezavo!");
}
}
but i always get Unhandled exception. Why?
At the risk of stating the obvious... Because you're not catching the Exception you throw in your catch block? Or, perhaps, something else is being thrown in the try block that isn't an OracleException.
What are you expecting to happen?
Just to be totally clear (to make sure that we're on the same page), an exception that's thrown but never caught will result in an unhandled exception (by definition). Throwing an exception from within a catch block is identical to throwing it from anywhere else; there still needs to be a try-catch somewhere to catch it. For example, this exception will be caught:
try {
throw new Exception("Out of cheese error"); // Caught below
}
catch (Exception) { }
But this one results in a new exception being propogated:
try {
throw new Exception("Out of cheese error"); // Caught below
}
catch (Exception) {
throw new Exception("418: I'm a teapot"); // Never caught
}
And this code catches both exceptions:
try {
try {
throw new Exception("Out of cheese error"); // Caught in inner catch
}
catch (Exception) {
throw new Exception("418: I'm a teapot"); // Caught in outer catch
}
}
catch (Exception e) {
Console.WriteLine(e.Message); // "418: I'm a teapot"
}
Your code does not in anyway swallow an exception. All it does is catch one type of exception and throw another type of exception. If you have an unhandled exception before you write this code, you will still have one after you write it.
--UPDATE --
Referring to your comment to another answer, if you want to display a message and stop executing code then try:-
catch (OracleException e)
{
Cursor.Current = Cursors.Default;
_instance = null;
if (e.ErrorCode == -2147483648) // {"ORA-01017: invalid username/password; logon denied"}
{
MessageBox.Show("Nepravilno ime uporabnika ali geslo");
}
else
{
MessageBox.Show("Ne morem se povezati na podatkovno bazo. Preveri povezavo!");
}
// this exits the program - you can also take other appropriate action here
Environment.FailFast("Exiting because of blah blah blah");
}
I assume you call hierarchy look like this:
Main
|-YourMethod
try {}
catch (OracleException) {throw new Exception("blah blah")}
So you see, the OracleException which occured in YourMethod is being caught by catch block, but then you throw a new one which goes into Main, where nothing handles it. So you should add an exception handler on the previous level.
Also, do not hide the original OracleException, throw your exception this way throw new Exception("your message", e). This will preserve the call stack.
Because you're only handling the OracleException. Nothing is handling the Exception() you are throwing.
You're catching the OracleException which means you're prepared to handle it - what does handling it mean to you? Logging it and moving on? Setting some state and moving on? Surely, you don't want to pop up gui in a data access component right? If you're not prepared to handle it, let it bubble up and handle it at an outer layer.
You also shouldn't throw exceptions of type Exception. Create your own strongly typed exceptions so they can be handled, or, simply log and call throw; which rethrows the original.
If you throw a new type of exception ensure you're passing the original exception as the inner exception to ensure you're not hiding details.
I did a write up on some best practices with C# exceptions:
Trying to understand exceptions in C#
Hope that helps