1

I am trying to get the ideal way to handle exception. I googled & read that I should put try catch in the catch block as well to handle but what if any exception occurs in the nested block itself.

try
{

            int a = 10;
            int b = 0;

            int c = a / b;

            Console.WriteLine(c);
            Console.ReadKey();
        }
        catch (Exception ex)
        {
            int a = 10; int b = 0;
            int c = a / b;
            Console.WriteLine(ex.Message.ToString());
            Console.ReadKey();
        }
        finally
        {
            Console.WriteLine("Some Exception");
        }

On googling I read that it should be decorated as below:

If I do this way, then it will stuck in an infinite try-catch block.

I think there would be some better or the right way to handle this scenario.

Community
  • 1
  • 1
Kgn-web
  • 7,047
  • 24
  • 95
  • 161
  • 1
    At some point, you should expect a crash if your code is an a state where you're getting exceptions in your exception handling. If an app crash isn't okay, you need to think about how your code can "bail out," or abort the process that's causing the issue. – Tieson T. Nov 17 '16 at 06:07
  • I would go with above comment. From my poing of view it is an design issue not a language issue. I could also build above example with `if` statements -> if that goes wrong, I performs failure handling -> if the failure handling goes wrong, I performs failure handling, If the .... – Moerwald Nov 17 '16 at 06:38
  • It is important that you learn very quickly that exception handling is **bad** _unless_ you have a specific exception that you are able to catch and that you can appropriately handle. If ever you write `catch (Exception...` you are probably making your life harder - not easier. – Enigmativity Nov 17 '16 at 13:08
  • 1
    @Enigmativity .. _exception handling is bad unless_ .. why?? .. _if ever you write catch (Exception... you are probably making your life harder - not easier_ .. how so?? **Exceptions** are bad .. exception **handling** is not and doesn't incur additional costs to the stack _unless_ there's an exception ... and given it's C# and not C, a few extra bytes for a stack trace on a bug you should have handled in the first place isn't that much compared to the .NET stack itself (GC, VM, etc.) ... – txtechhelp Nov 18 '16 at 03:33
  • @txtechhelp - Please read Eric Lippert's blog: https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/ – Enigmativity Nov 18 '16 at 04:34
  • @Enigmativity, I actually read that about 8 years ago when it was first published and we're in agreement, I should have error checked before catching ;) – txtechhelp Nov 18 '16 at 04:49

3 Answers3

3

I think there would be some better or the right way to handle this scenario.

No snark intended in this but simply, don't allow an exception to happen in the first place.

A try...catch is a language construct that ensures you handle an edge case or error you didn't mitigate and design for in the first place, hence why it's exceptional code.

In your code, you're simply throwing an error because of a division by 0, but in the real-world, you want to handle that and alert the user (or developer, or server, or whatever), and then handle the actual exceptional code, example:

static void PrintError()
{
    Console.WriteLine("You must enter a valid number between {0} and {1}, excluding 0", int.MaxValue, int.MinValue);
}

static void Main(string[] args)
{
    try {
        int a = 10;
        int b = 0;
        PrintError(); // Tell user to enter valid numbers
        while (b == 0) {
            string user_input = Console.ReadLine();
            if (int.TryParse(user_input, out b)) { // is it an actual number?
                if (b == 0) { // no 0's remember user!??
                    PrintError();
                } else {
                    // ok, everything checks out, so do what the system can actually handle without throwing an error
                    Console.WriteLine("a/b = {0}", (a / b));
                }
            } else {
                PrintError();
            }
        }
    } catch (Exception ex) {
        Console.WriteLine("Something exceptional happened: {0}", ex);
    }
}

This example could be simplified further, but it demonstrates there isn't an exception that could actually occur except something that is actually exceptional (i.e. out of memory error or some other system error).

In the event of larger code bases with multiple classes, the exception handler and finalizer would be where you could clean up resources acquired in other areas of the code, like closing a socket or file handle to ensure data is not lost.

In the event an error happens in the exception handler (something that can and does happen), you need to be aware of that and know what might happen in that case.

In the event of a C# application utilizing the .NET framework, an exception thrown within an exception will just cause the application to crash with the inner exception stack trace (versus the "outer" exception that's probably more relevant to the actual exception) if not handled.

There's plenty of "wrong" ways to handle exceptions (like not handling them at all), but there's not really a "right" way given the variable nature of exceptions.

Hope that can help.

txtechhelp
  • 6,625
  • 1
  • 30
  • 39
  • 1
    You can certainly throw an exception in an exception in c# .Net, it won't crash anything unless you leave it unhandled. – Stephen Turner Apr 24 '18 at 16:57
  • @StephenTurner .. yes, that is true and since that was not clear, I've updated the wording so as that's expressly unambiguous. – txtechhelp Apr 24 '18 at 21:43
  • 1
    There is also a long debate to be had as to where to draw the line between preventing exceptions and throwing and handling them properly. but this is not the place. – Stephen Turner Apr 26 '18 at 08:47
2

First of all you need to know what does try,catch and finally works lets start:

  1. Try: In this block we can write code which have the possibilities to throw some error (Better practice is to write code part in it.)

  2. Catch: It is responsible to show error and what to do if error arises(Like in your code 10/0 throws error which can be handled in this section.)

  3. Finally: Code written in this part will execute any how weather any error comes in or not.

Now for your query it would be better that you can use If...else in finally and code put in that part would be kept in try catch block.

For example:

bool flagCatch=false;
try
{

    int a = 10;
    int b = 0;

    int c = a / b;

    Console.WriteLine(c);
    Console.ReadKey();
}
catch (Exception ex)
{
    //Error handling
    flagCatch=true;
    Console.WriteLine(ex.Message.ToString());
    Console.ReadKey();
}
finally
{
    try
    {
        if(flagCatch)
        { 
            //Code
        }
        else
        {
            //Code when error not comes
        }
    }
    catch(Exception err)
    {
        //Error handling 
    }
}
Nayan Katkani
  • 806
  • 8
  • 18
0

I would go with the comment of Tieson T. . From my point of view it is an design issue.

I could also build an example with if statements -> if that goes wrong, I perform failure handling -> if the failure handling goes wrong, I perform failure handling, If the failure handling goes wrong ....

To make the code more readable, you can try to "hide" the try-catch blocks in method like:

static void PerformInTryCatch<T, TException>(Action<T> action, T obj) where TException : Exception
    {
        try
        {
            action(obj);
        }
        catch (TException exception)
        {
            // Perform some logging   
        }
    }

Hope that helps.

Moerwald
  • 10,448
  • 9
  • 43
  • 83