Catching exception of camera not avliable in C# - c#

I have the following C# code to start camera feed with pressing of button:
private void bntStart_Click(object sender, EventArgs e)
{
webcam.Start();
}
In case that the computer doesn't have a camera installed i get auto MSG error:
"an error occured while capturing the video image. The video capture will now be termenated. Object refrence not set to an istance of object"
My goal is to add my own error msg for the user. I tried the following :
private void bntStart_Click(object sender, EventArgs e)
{
try
{
webcam.Start();
}
catch (NullReferenceException exception)
{
MessageBox.Show(exception.Message);
return;
}
}
but nothing happend. any ideas? I tried to debug but on run time it never gets to the catch... maybe wrong exception?

You are assuming webcam.Start() throws a NullReferenceException, which i believe is not the case, you can try to catch the Exception (it's the base exception, but generally not a good practice), inspect the exception type while debugging and catch the actual exception and do what is required
private void bntStart_Click(object sender, EventArgs e)
{
try
{
webcam.Start();
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
return;
}
}

The Exception isn't catched, since it probably isn't a NullReferenceException, so that could mean webcam isn't equal to null.
You could try catching the error using Exception, change your code like this:
private void bntStart_Click(object sender, EventArgs e)
{
try
{
webcam.Start();
}
catch (Exception ex)
{
MessageBox.Show(String.Format("Something went wrong: {0}", ex.Message));
return; //Why is this return keyword here?
}
}
Why do you have return keyword in your code, while the method is at it's end already? Is this code made simple for posting here? I think it can be removed if so. Has nothing to do with your question tough.
It is possible to check for a NullReferenceException and an Exception, do this with following code:
private void bntStart_Click(object sender, EventArgs e)
{
try
{
webcam.Start();
}
catch(NullReferenceException nex)
{
MessageBox.Show(String.Format("NullReferenceException has been catched: {0}", ex.Message));
}
catch (Exception ex)
{
MessageBox.Show(String.Format("Something went wrong: {0}", ex.Message));
return; //Why is this return keyword here?
}
}

Is an exception even being thrown? You said you get an error message, but it's not clear from your description that this is actually an exception rather than the webcam library putting up its own messagebox.
If they're handling the error internally themselves and displaying a messagebox, you're out of luck - you can't catch what isn't being caught.

It seems like the error is caught and handled by the DLL itself. You're out of luck then. If there's no exception being thrown, there's nothing for you to catch. Unless you get access to the source code of the DLL, you're out of luck.

Related

How to ensure log the exception when there is unhandled exception

I want a crash reporting, so I register the UnhandledException event in App.xaml.cs like following. But there are 2 problems:
Sometimes, there is no callstacks for exception
Sometimes, I don't have enough time to write log into file before the process is terminated.
Any advice?
this.UnhandledException += App_UnhandledException;
private async void App_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (!hasHandledUnhandledException)
{
e.Handled = true;
_logger.Error("Unhandle exception - message = {0}\n StackTrace = {1}", e.Exception.Message, e.Exception.StackTrace);
await CrashHandler.ReportExceptionAsync(e.Exception.Message, e.Exception.StackTrace);
hasHandledUnhandledException = true;
throw e.Exception;
}
}
Make sure to access e.Exception only once. In some cases, information about the stacktrace is lost the second time you access the property. Save the exception in a variable and work directly with that variable. Also, as mentioned by Panagiotis Kanavos in the comments, directly log e.Exception.ToString() to make sure to miss no information. This will include the message, the callstack, and all inner exceptions (which you are not logging in your current code).
private async void App_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (!hasHandledUnhandledException)
{
e.Handled = true;
var exception = e.Exception;
_logger.Error("Unhandled exception - {0}", exception);
await CrashHandler.ReportExceptionAsync(exception.Message, exception.StackTrace);
hasHandledUnhandledException = true;
throw e.Exception;
}
}
As for the problem of not having enough time to log the exception, it's controlled by the runtime so you can't do anything about it.

Backgroundworker can't handle exception

I have a background worker that will throw an exception when there is a problem. I'm trying to catch the exception in the workcompleted event.
My code is roughly as follows:
void workerProcessReports_DoWork(object sender, DoWorkEventArgs e)
{
try
{
//Work is here. The code here throws an exception
}
catch (Exception ex)
{
throw ex;
}
}
void workerProcessReports_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show("There was a problem");
}
else
{
MessageBox.Show("No Problems");
}
}
The problem is that visual studio breaks on the throw ex in the dowork method with the Message
InvalidOperationException was unhandled by user code
What's going on?
Don't catch and rethrow your same exception, that's a waste and causes your stack trace to get messed up.
If you want the exact same exception to be thrown after catching it from a parent exception type, just write throw; in your catch block. If you plan on just throwing everything anyway, don't bother catching it in the first place.
If you do allow your exception to occur without handling it in the doWork method, then you can throw on the parent thread in your RunWorkerCompleted method.
Within your RunWorkerCompleted method you can throw it as such:
if(e.Error != null)
{
throw e.Error;
}
However, at this point if it's something you can handle you may just want to recover and continue, instead of throwing since you are already aware that an exception occured. Especially, if this parent thread is your UI thread, then this is the perfect opportunity to display an error message instead of throwing and potentially crashing your application for a non-fatal error.

Unhandled exceptions in infinite loop

I have a problem that I cannot seem to solve for a project. Consider this code:
namespace TestApp
{
class Program
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionsHandler);
int[] a = { 0, 1, 2 };
int y = a[6];
}
public static void UnhandledExceptionsHandler(object sender, UnhandledExceptionEventArgs e)
{
try
{
File.AppendAllText("Exceptions.log", (e.ExceptionObject as Exception).Message);
}
catch (Exception ex)
{
Environment.Exit(1);
}
}
}
}
The unhandled exception handler does in fact grab the unhandled exception as desired and write the message to log file. But on exiting the handler, the code resumes with the index out of range line: int y = a[6]. I need code to either move to the next line of code, or continue with the unhandled exception normally - in this case terminating the app. As it is, I'm stuck in an infinite loop of throw unhandled exception/hit the unhandled exception event handler.
You want try..finally in your handler:
try {
File.AppendAllText("Exceptions.log", (e.ExceptionObject as Exception).Message);
}
finally {
Environment.Exit(1);
}
What you have now is only catching an error that occurs when writing the log file. If there is no error (which there isn't).. it will finish the method and bubble back to the original exception.

Window closing bug or e.cancel = false but it won t totaly shut down

After 2+ hours of looking WHY my bloody process would not exit when I closed the window. I finaly found out that it was the problem in the main window(and not in a thread, because that could have been also the problem)! But I still got NO idea why it bugs.
So THIS code makes it bug:
private void Window_Closing(object sender, CancelEventArgs e)
{
try
{
MessageBox.Show(e.Cancel.ToString()); // False always
if (formcontroler.formchampinfo != null) // THIS IS NULL so it won t go into this IF
{
formcontroler.formchampinfo.Close(); // never gets here so it doesn t matter what this do right ?
}
MessageBox.Show(e.Cancel.ToString()); // always false, just to check or it would get to this part tbh
}
catch (Exception ex)
{
throw (ex); // never gets thrown
}
}
WHICH IS REALY Strange (to me)! because it gets to the 2nd messagebox and the e.cancel = FALSE so it should not cancel it and just shutdown and the process should get killed(and Visual studio should stop debugging).
Anyway it doesn t stop. It just keeps the process alife and I got no clue why, If I remove the middle if or replace it with a simpler one like:
private void Window_Closing(object sender, CancelEventArgs e)
{
try
{
MessageBox.Show(e.Cancel.ToString()); // False always
if (true == true) // just To test ofc
{
int lol = 5;
lol++;
}
MessageBox.Show(e.Cancel.ToString()); // always false, just to check or it would get to this part tbh
}
catch (Exception ex)
{
throw (ex); // never gets thrown
}
}
then it works and the program exits like it should(the process is killed and Visual studio stops debugging.
Some side code that shoudn t mattter I think
class formcontroler
{
public static frmchampinfo formchampinfo;
}
The frmchampinfo is a window, but atm I loaded it or declaterded it (like formchampinfo = new frmchaminfo();)
Is this a bug or what happened here ? I realy don t get why it doesn t shutdown totaly at my code.
SOLVED sorry I can t answer it until 7 hours but then I am asleep.(Because I don t got 100 rep yet)
Oke so after looking deeper and deeper I found out that the IF statement creates an other form in my formcontroller class(sorry I didn t provide full code in answer so you coudn t figure it out):
class formcontroler
{
public static frmchampinfo formchampinfo;
public static Window activeform;
public static frmlog formlog = new frmlog();
//... more code blabla
}
The formlog "gets made" here. If I add formcontroller.formlog.close() to the code then it can close completly.
private void Window_Closing(object sender, CancelEventArgs e)
{
try
{
MessageBox.Show(e.Cancel.ToString()); // False always
if (formcontroler.formchampinfo != null) // THIS IS NULL so it won t go into this IF
{
formcontroler.formchampinfo.Close(); // never gets here so it doesn t matter what this do right ?
}
formcontroler.formlog.Close(); // THIS FIXED IT... lame sorry for all your time. HoweveR I have learned something hope you did too.
MessageBox.Show(e.Cancel.ToString()); // always false, just to check or it would get to this part tbh
}
catch (Exception ex)
{
throw (ex); // never gets thrown
}
}
Check if the ShutdownMode of your App class is set to OnMainWindowClose.
You can also explicitly shutdown the application by:
Application.Current.Shutdown();

BackgroundWorker.IsBusy not 100% reliable?

I sometimes get an Exception that my BackgroundWorker is already running after checking it's state with the IsBusy method.
Code:
if(!_worker.IsBusy)
_worker.RunWorkerAsync(stateObj); //<-- exception is thrown here
I don't ever call the worker from anywhere else, so I'm stumped on how to handle this. Should I just ignore it? Or have it call itself?
(e.g.)
void CallWorker(object stateObj)
{
try
{
if(!_worker.IsBusy)
_worker.RunWorkerAsync(stateObj);
}
catch (Exception e)
{
//ignore OR
//CallWorker(stateObj);
}
}

Categories