Tuesday 18 October 2016

What will happen if exception will occur in exception block in c #?



If exception will occur in try block then exception or error is cached by catch block. If final block is with try catch then after exception final block will execute.
In some scenario, if exception occurs in catch block, then code will abort in catch block because no catch block is there for catching an error or exception. So we check our code and will use nested try catch in application.

Example:-
static void Main(string[] args)
        {


            try
            {
                int a = 10;
                int b = 0;
                int c = a / b;
                Console.WriteLine("divide by zero");
            }
            catch(Exception ex) // exception will catch here
            {
                string path=@"D:\Test\";
                File.Copy(path + "xml.xml", path + "xml.xml"); // trying to copy a file but here path does not exist so again exception throw and then code will abort
                Console.WriteLine("");
            }
            finally
            {
                Console.WriteLine("Final");
            }
        }
In the above example, exception will occur in try block and it will catch by catch block. But again exception will occur in catch block because path does not exist. So after that code will abort here means execution will stop here. So final block will not execute.
So according to you requirement or you know that exception will again occur in catch block then you use nested try-catch block.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.