How to use try catch finally in C#

1 Answer

0 votes
using System;
 
class Program
{
    static void Main()
    {
        string s = "c# programming";
        object obj = s;
        int i = 88;

        try {
            i = (int)obj; // try to cast string to int = Error

            Console.WriteLine("try");
        }
        catch (Exception ex) {
            Console.WriteLine("catch (Exception ex): {0}", ex.GetType());
        }
        finally {
            Console.WriteLine("\nfinally");
            Console.WriteLine("i = {0}", i);
        }
    }
}
 
 
 
 
/*
run:
 
catch (Exception ex): System.InvalidCastException

finally
i = 88
 
*/

 



answered Nov 23, 2020 by avibootz

Related questions

1 answer 164 views
164 views asked Jul 11, 2022 by avibootz
1 answer 224 views
224 views asked Jun 4, 2021 by avibootz
1 answer 390 views
2 answers 285 views
2 answers 286 views
1 answer 160 views
...