C#错误和异常类实例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 自定义错误类
{
class OutMaxExcption : Exception
{
public OutMaxExcption(string message)
:base(message)
{
}
}
class OutMinException : Exception
{
public OutMinException(string message)
: base(message)
{
}
}
class ValueIsZeroException:Exception
{
public ValueIsZeroException(string message)
: base(message)
{
}
}
class Program
{
static void Main(string[] args)
{
try
{
//throw new OutMaxExcption("测试"); //throw会阻断后面的语句执行,直接跳转到catch语句中
Console.WriteLine("请输入要访问的数组下标");
int inputNumber = int.Parse(Console.ReadLine());
if (inputNumber > 100)
{
throw new OutMaxExcption("超过最大值");
Console.WriteLine("已经抛出超过最大值错误"); //理论来说,这个语句永远不会执行
}
else if (inputNumber < 10 && inputNumber > 0)
{
throw new OutMinException("小于最小值");
Console.WriteLine("已经抛出小于最小值错误"); //理论来说,这个语句永远不会执行
}
else if (inputNumber == 0)
{
throw new ValueIsZeroException("值为零");
Console.WriteLine("已经抛出值为零错误"); //理论来说,这个语句永远不会执行
}
else if (inputNumber < 0)
{
throw new IndexOutOfRangeException("索引值不正确");
Console.WriteLine("已经抛出为负值错误"); //理论来说,这个语句永远不会执行
}
else if (inputNumber > 200)
{
/************嵌套的子try块和catch块***************/
try //可以在try块中去嵌套
{
if (inputNumber == 300)
throw new OutMaxExcption("严重超出最大值!");
}
catch (OutMinException ex) //嵌套的子catch块。如果抛出的错误在嵌套的子catch块中找不到合适的话,就会跳出嵌套子catch块到上一层catch块中查找
{
Console.WriteLine(ex.Message);
}
/************************************************/
}
else
Console.WriteLine("OK,输入正确");
}
//下面的代码为try块中抛出错误对应的捕捉catch分支。如果找不到具体的就执行catch(Exception ex)块它是万能的。
//同样的如果上面的嵌套的try块没有找到合适的catch分支就会跳出检索下面一群块
catch (OutMaxExcption ex)
{
Console.WriteLine(ex.Message);
}
catch (OutMinException ex)
{
Console.WriteLine(ex.Message);
}
catch (ValueIsZeroException ex)
{
Console.WriteLine(ex.Message);
}
catch (Exception ex) //此分支接受所有的异常类,如果与上面catch语句共存,此块优先上面的catch块
{
Console.WriteLine(ex.Message);
}
catch //如果catch没条件的话,它也可以接受所有错误的类,但是它与catch(Exception ex)共存的时候,程序会优先跳转到catch(Exception ex)语句中
{
Console.WriteLine("发生了错误!!!!!");
}
//下面的finally块无论上面的try块和catch块有没有执行都会执行finally的
finally
{
Console.WriteLine("这是finally块");
}
Console.ReadKey();
}
}
}