C#程序的异常处理

异常处理机制是保证程序健壮性的重要手段。

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TryCatchFinall
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "爱上C#编程!";                    //声明一个string类型的变量str
            object obj = str;                            //声明一个object类型的变量obj
            try                                    //使用try语句捕获异常
            {
                int i = (int)obj;                            //将obj强制转换成int类型
            }
            catch (Exception ex)                        //处理try语句捕获到的异常
            {
                Console.WriteLine(ex.Message);            //输出异常信息
            }
            finally                                    //finally语句
            {
                Console.WriteLine("finally语句被执行,程序执行完毕...");        
            }
            Console.ReadLine();
        }
    }
}

 

posted on 2017-09-07 16:35  stringAdmin  阅读(238)  评论(0编辑  收藏  举报

导航