📄 exceptionexample.cs
字号:
using System;
namespace Example_2
{
/// <summary>
/// ExceptionExample 的摘要说明
/// </summary>
class ExceptionExample
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此添加代码以开始应用程序
//
int userInput;
//无限循环
while(true)
{
//Try 语句块
try
{
Console.WriteLine("输入一个数字 (0-5): 键入 -1 以便退出");
userInput = Convert.ToInt32(Console.ReadLine());
//键入 -1 以便退出循环
if(userInput == -1)
break;
// 如果数字不在 0 与 5 之间,则将引发异常
if(userInput < 0 || userInput > 5)
throw new IndexOutOfRangeException("您键入的是 "+userInput);
Console.WriteLine("输入的数字为 "+userInput);
}
//处理 IndexOutOfRangeException
catch(IndexOutOfRangeException e)
{
Console.WriteLine("错误:数字应介于 0 与 5 之间。"+e.Message);
}
//处理一般异常
catch(Exception e)
{
Console.WriteLine("错误:"+e.Message);
}
finally
{
Console.WriteLine("退出 try 语句块");
}
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -