Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception handling within an Exception in C#

i know this could be a little weird but a doubt is a doubt afterall... what would happen in the following situation...

private void SendMail()
{
    try
    {
        //i try to send a mail and it throws an exception
    }
    catch(Exception ex)
    {
        //so i will handle that exception over here
        //and since an exception occurred while sending a mail
        //i will log an event with the eventlog

        //All i want to know is what if an exception occurs here
        //while writing the error log, how should i handle it??
    }
}

Thank you.

like image 415
Shrewdroid Avatar asked May 18 '10 09:05

Shrewdroid


People also ask

Can you catch exceptions in C?

C itself doesn't support exceptions but you can simulate them to a degree with setjmp and longjmp calls.

What is exception explain exception handling with example?

An exception occurs when an unexpected event happens that requires special processing. Examples include a user providing abnormal input, a file system error being encountered when trying to read or write a file, or a program attempting to divide by zero.

How many types of exception handling are there in C?

There are two types of exceptions: a)Synchronous, b)Asynchronous (i.e., exceptions which are beyond the program's control, such as disc failure, keyboard interrupts etc.).

Where exception are handled inside or outside?

Usually, the exception is caught inside the function and thrown from there so that it can be caught from where the function is called so that a proper remedy can be given depending on the parameters passed to the function.


3 Answers

I would personally wrap the call to write to event log with another try\catch statement.

However, ultimately it depends on what your specification is. If it is critical to the system that the failure is written to the event log then you should allow it to be thrown. However, based on your example, I doubt this is what you want to do.

like image 180
Robben_Ford_Fan_boy Avatar answered Oct 13 '22 22:10

Robben_Ford_Fan_boy


You can simply catch errors in the error logging method. However I wouldn't personally do that, as broken error logging is a sign your application can't function at all.

private void SendMail()
{
    try
    {
        //i try to send a mail and it throws an exception
    }
    catch(Exception ex)
    {
        WriteToLog();
    }
}

private void WriteToLog()
{
    try
    {
        // Write to the Log
    }
    catch(Exception ex)
    {
        // Error Will Robinson
        // You should probably make this error catching specialized instead of pokeman error handling
    }
}
like image 21
Chris S Avatar answered Oct 14 '22 00:10

Chris S


Each exception is caught only when inside a try-catch block. You could nest try-catch but is generally not a good idea.

like image 1
VoodooChild Avatar answered Oct 13 '22 23:10

VoodooChild