Got a strange problem: in a complex camera control program I'm working on, I use an SDK with a C# wrapper that was programmed by someone else. I include the wrapper as a separate project within the same solution. My own code is a WPF project that uses numerous calls into the SDK.
Everything synchronous works fine. However, depending on camera responses, the SDK occasionally sends asynchronous responses, usually in the form of throwing a custom exception with info about an error the camera reports. I implemented this using
try { ... } catch (ThisExceptionType) { ... }
However, NO exception ever gets caught. When an exception situation occurs, VisualStudio breaks, shows me the code where the SDK throws it and reports "ThisExceptionType was unhandled by user code", also showing the details of the exception condition (meaning it was apparently thrown properly). I verified that the exception corresponds with the error condition I created, so I'm sure I'm not looking at the wrong part of my code.
For testing purposes, I also replaced the line in the SDK where it throws ThisExceptionType with a standard exception, such as throw new ArgumentException("Test"); Same result: when changing my catch to catch (ArgumentException), I still cannot catch the condition and get a similar unhandled-by-user-code error.
Here's how the SDK throws the exception:
void CallEntryPoint( ...)
{
eNkMAIDResult result = _md3.EntryPoint(...);
switch (result)
{
// Note: Ignore these return values
case eNkMAIDResult.kNkMAIDResult_NoError:
case eNkMAIDResult.kNkMAIDResult_Pending:
break;
default:
throw new NikonException(...);
}
}
What am I missing here? Sorry if this is a simple issue - I'm pretty experienced in general programming but have not worked much with VisualStudio, and not a whole lot in C#, either.
UPDATE: According to the wrapper's author (this is actually Thomas Dideriksen's Nikon SDK wrapper), "when you're writing WPF or WinForms application, the C# wrapper relies on the inherent windows message queue to fire events on the UI thread."
He also states that the wrapper processes all camera tasks sequentially, so I guess my statement was incorrect about the wrapper throwing asynchronous exceptions - all code examples for the wrapper use the same try { ... } catch (ThisExceptionType) { ... } approach. For good measure, I tried some of your suggestions, for instance by hooking a handler to AppDomain.CurrentDomain.UnhandledException, but that approach failed to catch the exception, as well.
Any other ideas why this may be happening?
This article on MSDN may help. https://msdn.microsoft.com/en-us/library/dd997415(v=vs.110).aspx
There are differences in handling exceptions using Tasks in C#. Hopefully that will give a run down on different techniques you can use to handle the exceptions appropriately.
From the MSDN article:
Unhandled exceptions that are thrown by user code that is running
inside a task are propagated back to the calling thread, except in
certain scenarios that are described later in this topic. Exceptions
are propagated when you use one of the static or instance Task.Wait or
Task.Wait methods, and you handle them by enclosing the call
in a try/catch statement. If a task is the parent of attached child
tasks, or if you are waiting on multiple tasks, multiple exceptions
could be thrown.
And there are a couple solutions provided:
using System;
using System.Threading.Tasks;
public class Example
{
public static void Main()
{
var task1 = Task.Run( () => { throw new CustomException("This exception is expected!"); } );
try
{
task1.Wait();
}
catch (AggregateException ae)
{
foreach (var e in ae.InnerExceptions) {
// Handle the custom exception.
if (e is CustomException) {
Console.WriteLine(e.Message);
}
// Rethrow any other exception.
else {
throw;
}
}
}
}
}
public class CustomException : Exception
{
public CustomException(String message) : base(message)
{}
}
// The example displays the following output:
// This exception is expected!
Or you can do this:
using System;
using System.Threading.Tasks;
public class Example
{
public static void Main()
{
var task1 = Task.Run( () => { throw new CustomException("This exception is expected!"); } );
while(! task1.IsCompleted) {}
if (task1.Status == TaskStatus.Faulted) {
foreach (var e in task1.Exception.InnerExceptions) {
// Handle the custom exception.
if (e is CustomException) {
Console.WriteLine(e.Message);
}
// Rethrow any other exception.
else {
throw e;
}
}
}
}
}
public class CustomException : Exception
{
public CustomException(String message) : base(message)
{}
}
// The example displays the following output:
// This exception is expected!
I hope that helps!
Related
I have a new application that contains great amount of try-catch blocks. I am interested in if it is possible to write code which somehow attachs SaveExceptionInDatabase method to every catch-block I have used in my application.
try
{
//some actions
}
catch(exception e)
{
SaveExceptionInDatabase(e,DateTime.now(),CurrentUser);
ShowFriendlyNotification();
}
I think it will be helpful to easily remove bugs from my application, because I have noticed for several times that after the exception is thrown, attempting to perform the same operation second time finishes with success.
EDIT:
I am using WPF With Caliburn.Micro
You could use PostSharp and handle the exceptions. Here are some related articles that show how it can be done. This method seems really cool because you can just add an attribute to your classes an have the exceptions handled.
[DatabaseExceptionWrapper]
http://www.postsharp.net/blog/post/Day-1-e28093-OnExceptionAspect
http://www.postsharp.net/blog/post/Improve-Exception-Handling-and-Caching-using-PostSharp
You can use something like:
private void HandleDbException(Action action)
{
try
{
action();
}
catch (Exception e)
{
SaveExceptionInDatabase(e, DateTime.now(), CurrentUser);
ShowFriendlyNotification();
}
}
And then
HandleDbException(() =>
{
//some actions1
});
HandleDbException(() =>
{
//some actions2
});
...
It won't apply the pattern to each try/catch block in your code but at least avoids repeating the catch block.
This is somewhat of a follow up to a previous question I had asked, although I am now able to provide a lot more code to improve my question and further show my trouble with this area.
I have three routines here. Two of these routines work together - and if successful, will load an assembly into memory using System.Reflection. I would like for these routines to return an error if the file did not load properly into memory, but for some reason these try-catch statements simply will not work the way I would like.
Note: For this routine to work the file must be a .net assembly. If, for example, the file was programmed in VB6 an error will be thrown. This is the error I am trying to have returned to me.
private void ExecuteDataIntoMemory(string filePath)
{
byte[] bytes = File.ReadAllBytes(filePath);
try
{
ExecFile(bytes);
MessageBox.Show("successfully loaded this file into memory");
}
catch
{
MessageBox.Show("Could not load this file into memory");
}
}
private static void ExecFile(byte[] data)
{
try
{
//Work around for "SetCompatibleTextRenderingDefault"
System.Threading.Thread T = new System.Threading.Thread(ExecFile);
//Set STA to support drag/drop and dialogs?
T.SetApartmentState(System.Threading.ApartmentState.STA);
T.Start(data);
}
catch
{
MessageBox.Show("caught some error ...");
}
}
private static void ExecFile(object o)
{
System.Reflection.MethodInfo T = System.Reflection.Assembly.Load((byte[])o).EntryPoint;
if (T.GetParameters().Length == 1)
T.Invoke(null, new object[] { new string[] { } });
else
T.Invoke(null, null);
}
I can clarify more if necessary but I'm not sure what other information to include at this point.
Use the "throw" statement within the catch statement of ExecFile to raise the same "exception" (or error) caught in ExecFile. For example:
catch {
throw;
}
I think I figured out the problem though. ExecFile(byte[]) starts the thread and returns immediately without waiting for the thread to exit. To allow that method to wait for the thread to exit, add:
T.Join();
right after starting the thread. (To avoid possible ambiguity, however, you should rename ExecFile(object). I'm also not sure whether ExecFile(byte[]) will catch the exception from ExecFile(object).)
If I understand you well, You want the ExecuteDataIntoMemory to be evaluated only if the ExecFile succeed.
1- You are running a new thread to execute the ExecFile method which will be executed in a different thread. So first at the try block in ExecFile(byte[] data) run the ExecFile(data) without a new Thread because you want to wait for it any way:
try
{
ExecFile(data);
}
2- Notice that you have two method with the same name 'ExecFile(byte[] data)' and ExecFile(object o) the data you are passing is from type byte[] so it will be infinite recursive or till stack over flow exception is raised. So you should cast data to object and then pass it to the method i.e:
try
{
ExecFile((object)data);
}
3- At the catch block of the ExecFile(byte[] data) method rethrow the exception so it can be handled from the caller method two i.e:
try
{
ExecFile((object)data);
}
catch
{
MessageBox.Show("caught some error ...");
throw;
}
If you catch the Exception in ExecFile(byte[] data) it won't be propagated in your parent method (ExecuteDataIntoMemory(string filePath)), and then won't be catched again
If you really need to catch your exception twice, rewrite your child method this way
private static void ExecFile(byte[] data)
{
try
{
//Work around for "SetCompatibleTextRenderingDefault"
System.Threading.Thread T = new System.Threading.Thread(ExecFile);
//Set STA to support drag/drop and dialogs?
T.SetApartmentState(System.Threading.ApartmentState.STA);
T.Start(data);
}
catch (Exception ex)
{
MessageBox.Show("caught some error ...");
throw ex;
}
}
If not, simply not try..catch errors in this method, and the Exception will be propagated..
Just look in the callstack which method call the ExecuteDataIntoMemory method again?
if you are using Visual studio IDE put a breakpoint at the messagebox:
MessageBox.Show("successfully loaded this file into memory");
then simple go to the view menu, from there find the callstack window to display and look at the callstack (show external code to the callstack)
maybe this could help.
The rough way (I think), but should work in your case, is subscribe to
AppDomain.CurrentDomain.UnhandledException
event riased, which will get the exception raised directly from the function ExecFile(object o);
Or create a state machine which is set to NEGATIVE state in case of any exception in ExecFile(object o); method.
Or just do not do it in multithreading :)
following is a code snippet:
class xxx
{
public xxx(){}
try
{
throw new Exception(InvalidoperationException);
}
catch(Exception x)
{
}
catch(InvalidoperationException x)
{
}
}
can anyone tell which exception will raise here and what is the reason behind it.
Wow, lots of problems here. Where to start?
That code won't compile. The try-catch block that you've defined is outside of any method, which is not allowed. You need to move it inside of a method.
Never throw a method that you intend to catch yourself later in the method. That's commonly known as using exceptions for "flow control", which is roundly discouraged. There is a performance cost associated with doing so, and it also makes it very confusing to monitor the exceptions that are being thrown when using a debugger when you have code that's throwing and catching it's own exceptions. Use boolean variables (known as flags) for flow control, if necessary.
Always catch the most derived exception class first. That means you should catch InvalidOperationException first, before trying to catch Exception. You need to reverse the order of your catch blocks in the code that you have.
You should practically never catch System.Exception. The only exceptions that you should catch are those that you explicitly understand and are going to be able to handle. There's virtually no way that you're going to know what went wrong or how to handle it when the only information you have is that a generic exception was thrown.
Along those same lines, you also should never throw this exception from your own code. Choose a more descriptive exception class that inherits from the base System.Exception class, or create your own by inheriting from the same.
I see that other answers are showing you sample code of what your code should look like, were it to be rewritten. I'm not going to do that because if I rewrote your code to be correct, I'd end up with this:
class Xxx
{
public Xxx()
{
}
}
Not particularly helpful.
If the code is like this
class xxx
{
public xxx(){
try
{
throw new Exception(InvalidoperationException);
}
catch(InvalidoperationException x)
{
}
catch(Exception x)
{
}
}
}
It should compile and raise your exception and catch. Otherwise your code will not compile at all.
No exception will be thrown as this code will not even compile.
Regardless - several points:
When using exception handling, put the more specific exception before the less specific ones (so the catch of InvalidOperationException should be before the one for Exception).
Catching Exception is normally no very useful.
If you catch an exception, do something with it.
You probably meant:
throw new InvalidOperationException();
However, the way you structured your exceptions, the catch(Exception x) block would have run.
You should write:
class xxx
{
public void Test()
{
try
{
throw new InvalidoperationException();
}
catch(InvalidoperationException exception)
{
// Do smth with exception;
}
catch(Exception exception)
{
throw; // Rethrows your exception;
}
}
}
InvalidOperationException inherits from Exception.
catch tries to processes the most specific branch, so catch (InvalidOperationException x) will be executed here.
Nope. It wouldn't compile. So, it there's no question about as to which exception will be generated.
Your code should be something like this :
class xxx
{
public void Test()
{
try
{
throw new InvalidoperationException();
}
catch(InvalidoperationException exception)
{
// Something about InvalidOperationException;
}
catch(Exception exception)
{
// Something about the Exception
}
}
}
Point to be noted :
Write more specific class of Exception first, hence we write InvalidOperationException prior to Exception class.
Ignoring the compile issue.... the first matching exception block (catch(Exception x)) will get the exception. You then ignore the exception and don't re-throw, so exception will be seen by the outside world. That doesn't make it good practice, though... in particular, catching an arbitrary Exception and ignoring it is risky - it could have been anything... it isn't necessarily the exception you thought it was.
Well, the code won't compile, but I'll just ignore that...
If I'll just look at the line:
throw new Exception(InvalidoperationException);
1st of all, according to MSDN there is no such constructor. So I will assume you meant the constructor: Exception(String msg, Exception innerException). Meaning:
throw new Exception("blabla", InvalidoperationException);
The exception that is being thrown is of type Exception and not InvalidOperationException. So ONLY catch(Exception x) can catch it.
If you would've thrown InvalidoperationException than the way you wrote the order of the catches, the Exception class would get caught first.
The order of the catches does matter.
The best advice I can give you is simply try it yourself and see what happens.
Probably a stupid question... but here goes anyway...
I have set up quartz, and can schedule jobs, and I can confirm that jobs (implementing the IJob interface) are working.
Looking at the documentation on the site, (Lesson 3 of the tutorial):
The only type of exception that you are allowed to throw from the execute method is JobExecutionException.
I would like that when an exception occurs that I haven't explicitly handled, it should throw a JobExecutionException, so that I can log it in the 'parent' application. I have wrapped my code in a try catch, and have thrown the JobExecutionException, but now where to handle it?
I don't call the execute method anywhere, that is handled by Quartz (on a separate thread). So, how do I handle that error when it occurs. I don't really want to swallow the error in the Job
I solved this problem by using a base class to catch all the exceptions:
public abstract class JobBase : IJob
{
protected JobBase()
{
}
public abstract void ExecuteJob(JobExecutionContext context);
public void Execute(JobExecutionContext context)
{
string logSource = context.JobDetail.FullName;
try
{
ExecuteJob(context);
}
catch (Exception e)
{
// Log exception
}
}
}
Your Job class should like this:
public class SomeJob : JobBase
{
public SomeJob()
{
}
public override void ExecuteJob(JobExecutionContext context)
{
// Do the actual job here
}
}
Typically you would set up the execute method of your job as follows:
try
{
// the work you want to do goes here
}
catch (ExceptionTypeYouWantToHandle1 ex1)
{
// handle exception
}
catch (ExceptionTypeYouWantToHandle2 ex2)
{
// handle exception
}
// and so on
catch (Exception ex)
{
// something really unexpected happened, so give up
throw new JobExecutionException("Something awful happened", ex, false); // or set to true if you want to refire
}
At this point the scheduler itself will log the exception to wherever it is logging (based on the configuration).
As already mentioned, the correct way to "detect" JobExecutionException's on a global level is to implement and register an IJobListener and check if the JobExecutionException parameter in the JobWasExecuted() method is != null.
However, the problem I had (and judging from the additional comment of the OP, he faced this too) was that Quartz did not handle the JobExecutionException (as it should) which resulted in an unhandled exception killing the application.
So far, I was using the precompiled DLL from the Quartz.NET 2.0.1 release (.NET3.5) package. To get to the bottom of the problem, i referenced the Quartz project/sourcecode and to my astonishment it was suddenly working?!
As a point of interest, this is the Quartz library code that executes the IJob and handles the JobExecutionException:
try {
if (log.IsDebugEnabled) {
log.Debug("Calling Execute on job " + jobDetail.Key);
}
job.Execute(jec);
endTime = SystemTime.UtcNow();
} catch (JobExecutionException jee) {
endTime = SystemTime.UtcNow();
jobExEx = jee;
log.Info(string.Format(CultureInfo.InvariantCulture, "Job {0} threw a JobExecutionException: ", jobDetail.Key), jobExEx);
} catch (Exception e) {
// other stuff here...
}
The next thing was to reference my freshly compiled DLL direcly and this was working as well. Sadly i can't tell you why this works and i currently don't have any time to get into it any further, but maybe this helps someone. Maybe some else can confirm this and even contribute an explanation. It may have something to do with different target platforms (x86/64bit)?
I have the following try-catch statement and I do not want to not throw the exception if the message property contains 'My error' in the text.
How can I programmatcially accomplish this? Also, would this be considered code-smell?
try
{
}
catch(Exception e)
{
if(e.Messages.Contains("My error"))
{
//want to display a friendly message and suppress the exception
}
else
{
throw e;
}
}
You shouldn't catch errors based on the error test. You should make your own exception class that extends exception:
class MyErrorException : Exception { }
and throw and catch those. (Excuse my syntax if it's wrong, I haven't done C# in a while).
That being said, throwing and catching your own Exceptions instead of propagating them is perfectly normal, and it is how you actually should do exception handling.
You should be catching the specific exception you're looking for. Quite frankly, that code is shocking. You should have something like ...
public class MyCoolException : Exception {
public MyCoolException(string msg) : base(msg) {}
}
public void MyCoolMethod() {
// if bad things happen
throw new MyCoolException("You did something wrong!");
}
Then later in your code you can use it like ...
try {
MyCoolMethod();
} catch (MyCoolException e) {
// do some stuff
}
Your code creates maintainability issues because a simple text change can have strange side effects. You can have your own exception class which inherits from System.Exception. Then instead of having an if you could do the following:
try
{
}
catch(MyException myException) //or just catch(MyException)
{
//display a friendly message
}
also you don't want to do throw e because it doesn't preserver the Stack, just throw; will do.
When I throw Exception rather than a derived class I always mean a failed assertion. I don't like failing out the backend because we are still able to receive a request (just not that one again). If we're really toast it will just error out on the next request anyway.
When the back end needs to generate an error message I have a ErrorMessage class that inherits from Exception and takes ErrorMessage and ErrorMessageTitle as constructor arguments.