C#错误和异常处理典型例子

检查用户输入的是否是一个0-5中间的数字: 多重catch块

 

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

namespace ExceptionDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string userInput;

            while (true)
            {
                try
                {
                    Console.Write("Input a number between 0 and 5" + "(or just hit return to exist)>");
                    userInput = Console.ReadLine();

                    if (userInput == "")
                        break;

                    int index = Convert.ToInt32(userInput);

                    if (index < 0 || index > 5)
                        throw new IndexOutOfRangeException("You typed in  " + userInput);

                    Console.WriteLine("Your number was " + index);
                }
                catch (IndexOutOfRangeException ex)
                {
                    Console.WriteLine("Exception: " + "Number should between 0 and 5." + ex.Message);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("An exception was thrown. Message was: {0}" + ex.Message);
                }
                catch
                {
                    Console.WriteLine("Some other exception has occured");
                }
                finally
                {
                    Console.WriteLine("Thank you");
                }
            }
        }
    }
}

当输入的是非0-5之间的数字的时候,抛出的第一个异常,如果是一个字符串,抛出的第二个异常。第三个异常不带参数,这个catch块处理的是其他没有用C#编程的代码。

 

下面这个是MSDN一个try…finally的异常处理

static void CodeWithCleanup()
        {
            System.IO.FileStream file = null;
            System.IO.FileInfo fileInfo = null;

            try
            {
                fileInfo = new System.IO.FileInfo("C:\\file.txt");

                file = fileInfo.OpenWrite();
                file.WriteByte(0xF);
            }
            catch (System.Exception e)
            {
                System.Console.WriteLine(e.Message);
            }
            finally
            {
                if (file != null)
                {
                    file.Close();
                }
            }
        }

转载于:https://www.cnblogs.com/herbert/archive/2010/06/28/1766826.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值