How to handle exception in catch block?

前端 未结 3 1889
半阙折子戏
半阙折子戏 2021-01-24 03:33

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 handl

相关标签:
3条回答
  • 2021-01-24 03:41

    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.

    0 讨论(0)
  • 2021-01-24 03:46

    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.

    0 讨论(0)
  • 2021-01-24 04:01

    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 
        }
    }
    
    0 讨论(0)
提交回复
热议问题