How to handle exception in catch block?

前端 未结 3 1896
半阙折子戏
半阙折子戏 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 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 
        }
    }
    

提交回复
热议问题