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
Related
I'm having an issue with a try/catch block, but I can't seem to find out exactly how try/catch works when it's running that I think might have my answer. I have the following try/catch block:
try
{
...
}
catch (MyException e)
{
Log.Error("oh no!");
throw;
}
Now when I run this code I'm getting a System.TypeLoadException: Could not load type SDK.MyException from assembly "SDKSampleLibrary, Version... etc error.
I'm wondering 2 things. First, when does the computer check to see if MyException is there. Is it when it gets to the try or when it gets to the catch? Second, the SDKSampleLibrary.dll is there. How do I tell why it's not seeing it?
If the class MyException gets thrown within the try area, it will get handled inside the catch, See my example below where i throw a new exception which would get handled by the catch statement. However any other kinds of exceptions would not be handled/
try
{
throw(new MyException()); // handled by the catch
throw(new ParseException()); //not handled.
int test = "test" //not handled
}
catch (MyException e)
{
Log.Error("oh no!");
throw;
}
can also catch general exceptions to catch ALL exceptions like:
try
{
throw(new MyException()); // handled by the catch
throw(new ParseException()); //handled.
int test = "test" //handled
}
catch (Exception e)
{
Log.Error("oh no!");
throw;
}
The compiler sees the class since it is blue and does not give compile errors. The problems is happening when you are running the code. I think the problem is in de code that throws the exception which cannot create it. You could try to use the normal Exception type in the catch block and then set a break point.
The problem is not with the try/catch block but rather the problem is the type of exception that you are trying to catch as specified by the exception that your code is throwing. This exception occurs when the runtime tries to load the MyException object. You should make sure that the MyException inherits either from the Exception base class or from any of its children.
if I do this:
try
{
//code
}
catch (Exception)
{
throw;
}
Does the Exception go up with all its information?
The idea is to handle errors at the top of the app. There I'd execute some SQL sp to fill the admin's table so he's aware of exceptions.
I want to store Exception.Message and the source (method, function, whatever..) of the exception. But I don't know how to refer to "where" the exception happened. Is it Exception.Source? Exception.TargetSite?
Thanks.
The type of Exception will tell you what kind of exception it is (IndexOutOfRangeException, SqlException, etc) which you would react too accordingly:
try
{
//code
}
catch (SqlException ex)
{
// Handle code
}
catch (IndexOutOfRangeException ex)
{
// Handle code
}
catch (Exception ex)
{
// Handle code
}
As to where it is happening... you should be enclosing exception-prone areas with a try catch and not large code chunks. This way you will know where the exception derives from.
The Short answer is yes: just calling throw passes everthing regarding the exception up.
throw ex resets the stack trace (so your errors would appear to originate from HandleException)
throw doesn't - the original offender would be preserved.
(quoted from Mark Gravell)
While using this code
try
{
transfer.TransferData();
}
catch (SmoException smoex)
{
//Do something
}
catch (Exception ex)
{
//Do something else
}
The exception is always caught by the second catch statement.
Does someone know why this happens?
Thanks in Advance
Use this to determine what the exception you get actually is:
try
{
transfer.TransferData();
}
catch (Exception ex)
{
var theRealExceptionTypeName = ex.GetType().Name;
}
This happens because the exception is not an SmoException.
It is either an Exception or another exception type deriving from Exception, but not SmoException. SmoException would be caught by the first handler if it were truely an SmoException or a class deriving from SmoException. Hopefully that sentence isn't as confusing to read as it was to type!
Further reading on exceptions and exception handling:
http://msdn.microsoft.com/en-us/library/ms173160(v=vs.80).aspx
Documentation doesn't say what exceptions are thrown:
http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.transfer.transferdata.aspx
try
{
try
{
throw new Exception("From Try");
}
catch
{
throw new Exception("From Catch");
}
finally
{
throw new Exception("From Finally");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
The above code's output is: From Finally.
Why it's not From Catch?
-or-
How can i catch & log from outside both exceptions?
Because the finally block executes after the catch block, overriding the exception.
And when an exception happens during the handling of an earlier one, the first one is lost.
How can i catch & log from outside both exceptions?
By not throwing inside a finally block. That is always a bad idea.
If you want to log in an inner catch block use throw; or pass the first exception as InnerException of the new one. That is why InnerException exists.
This is the behaviour as it is defined by the C# language specification. Handling of the exception thrown inside the try block is aborted and instead the exception thrown in the finally block will be handled.
The relevant section 8.9.5 The throw statement explains how exceptions are propagates:
In the current function member, each try statement that encloses the throw point is examined. For each statement S, starting with the innermost try statement and ending with the outermost try statement, the following steps are evaluated:
If the try block of S encloses the throw point and if S has one or more catch clauses, the catch clauses are examined in order of appearance to locate a suitable handler for the exception. The first catch clause that specifies the exception type or a base type of the exception type is considered a match. A general catch clause (ยง8.10) is considered a match for any exception type. If a matching catch clause is located, the exception propagation is completed by transferring control to the block of that catch clause.
Otherwise, if the try block or a catch block of S encloses the throw point and if S has a finally block, control is transferred to the finally block. If the finally block throws another exception, processing of the current exception is terminated. Otherwise, when control reaches the end point of the finally block, processing of the current exception is continued.
Add an extra layer of try-catch blocks like the following:
try {
Exception fromCatch = null;
try {
throw new Exception("From Try");
}
catch {
try {
throw new Exception("From Catch");
}
catch (Exception e) {
// catch failed -> store exception
fromCatch = e;
}
}
finally {
try {
throw new Exception("From Finally");
}
catch (Exception e) {
// i can think of better exception merging... but this shows the idea
throw new Exception(e.Message, fromCatch);
}
// throw fromCatch, in case "From Finally did not happen"
throw fromCatch;
}
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
if (ex.InnerException != null) {
Console.WriteLine(ex.InnerException.Message);
}
}
Reports:
From Finally
From Catch
Edit: this is obviously the answer for question two, as the "why" is answered sufficiently :)
finally always runs; and it always runs last. So the lat thing done by the inner try was the finally and that threw something that was caught by the outer catch
not sure if i understand part2 of the question
finally happens no matter what. Regardless of whether there was an exception in the try or catch. Thus, you see "From Finally". (This actually is the entire purpose of the finally clause. So you can put code in there that will clean up resources and the like no matter what -- even if there's an exception.)
Your code throws a new Exception from each part of the try/catch/finally statement. You are essentially swallowing the previous exception when you create the new error. You can add your "From Try" message to your "From Catch" message with something like
catch(Exception ex)
{
throw new Exception(ex.Message + ":" + "From Catch");
}
I don't know know how you could chain that in the finally though.
This is a very good question, and one that is kind of tricky. Let's go through this step by step:
try
{
throw new Exception("From Try");
}
catch
{
throw new Exception("From Catch");
}
In the code above, Exception("From Try") is thrown and caught by the catch clause (pretty simple so far). The catch clause throws an exception of it's own, which normally we would expect (because the catch is nested in a larger try-catch block) to be caught immediately, but...
finally
{
throw new Exception("From Finally");
}
The finally clause, which is guaranteed to (try to) execute, comes first, and throws an exception of it's own, overwriting the Exception("From Catch") that was thrown earlier.
"A common usage of catch and finally
together is to obtain and use
resources in a try block, deal with
exceptional circumstances in a catch
block, and release the resources in
the finally block" - MSDN Article
Following this train of logic, we should try our best to refrain from writing code in our catch and finally blocks that is exception-prone. If you're worried about situations like the one you presented cropping up, I'd recommend logging the exceptions and their related information out to an external file, which you can reference for debugging.
Because the finally block is always executed.
try
{
try
{
throw new Exception("From Try");
// (1) A new exception object A is created here and thrown.
}
catch // (2) Exception object A is catched.
{
throw new Exception("From Catch");
// (3) A new exception object B is created here and thrown.
}
finally // (4) Execution is forced to continue here!
{
throw new Exception("From Finally");
// (5) A new exception object C is created here and thrown.
}
}
catch (Exception ex) // (6) Exception object C is catched.
{
Console.WriteLine(ex.Message);
}
Every new'd exception object in step (3) and (5) discards the previous one. Since the finally block is always executed all what remains is the exception object C from step (5).
What happens if both catch and finally blocks throw exception?
When the finally block throws an exception, it will effectively hide the exception thrown from the catch block and will be the one ultimately thrown. It is therefore important to either log exceptions when caught, or make sure that the finally block does not itself throw an exception, otherwise you can get exceptions being thrown that are stifled and never seen.
When catch throws an exception, finally block will be run and then exit with an exception.
If the finally block throws an exception, the block will exit with an exception.
The last exception thrown is thrown.
Its already been answered well by adrianbanks, but the following post should be interesting:
Interesting Exception Results: Throwing Exceptions From the Finally Block
HI Nwaman i think you answer is wrong i have tested it in windows appliaction, i found if u write a program like the below one
try
{
string s = "hu";
int i = int.Parse(s);
}
catch (Exception ex)
{
string s = "hu";
int i = int.Parse(s);
throw new Exception();
}
finally
{
MessageBox.Show("hi");
}
and this will not result finally to excute,