人总是会有犯错的一天,
程序想必也是如此,
但犯错之後该怎麽办呢?
我们今天来探讨C#的错误处理
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CsharpDemo
{
class Program
{
static void Main(string[] args)
{
//宣告分子
int x = 100;
//宣告分母
int y = 0;
int z = x / y;
Console.WriteLine("结果 : " + z);
Console.ReadKey();
}
}
}
结果:
未处理的例外状况: System.DivideByZeroException: 尝试以零除。
於 CsharpDemo.Program.Main(String[] args) 於 C:\CsharpDemo\Program.cs: 行 21
我们会发现程序抛出了一个DivideByZeroException类别的错误,来提醒开发者发生什麽事情了
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CsharpDemo
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("请输入分母");
//宣告分子
int x = 100;
//宣告分母
int y = Convert.ToInt32(Console.ReadLine());
int z = x / y;
Console.WriteLine("结果 : " + z);
}
catch (DivideByZeroException)//捕捉分母为0的错误
{
Console.WriteLine("分母不可以为0");
}
catch (FormatException)//捕捉格式错误
{
Console.WriteLine("格式不正确");
}
Console.ReadKey();
}
}
}
输入:
0
结果:
请输入分母
0
分母不可以为0
输入:
孤独一只鸡
结果:
请输入分母
孤独一只鸡
格式不正确
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CsharpDemo
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("请输入分母");
//宣告分子
int x = 100;
//宣告分母
int y = Convert.ToInt32(Console.ReadLine());
int z = x / y;
Console.WriteLine("结果 : " + z);
}
catch (Exception ex)//捕捉所有发生的错误,如果不知道可能会发生的错误可以使用此类别
{
//ex.Message可得到简易的错误描述,如果需要详情,建议使用 ex.ToString()
Console.WriteLine(ex.Message);
}
finally//最终要处理的事情
{
Console.WriteLine("既然都犯错了,那就收工吃饭吧!");
}
Console.ReadKey();
}
}
}
输入:
0
结果:
请输入分母
0
尝试以零除。
既然都犯错了,那就收工吃饭吧!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CsharpDemo
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("请输入1~10任一数");
int number = Convert.ToInt32(Console.ReadLine());
//判断是否有超过范围
if (number < 1 || number > 10)
{
//抛出超出范围的异常
throw new IndexOutOfRangeException();
}
else
{
Console.WriteLine("你输入了 : " + number);
}
}
catch (Exception ex)//捕捉所有发生的错误,如果不知道可能会发生的错误可以使用此类别
{
//ex.Message可得到简易的错误描述,如果需要详情,建议使用 ex.ToString()
Console.WriteLine(ex.Message);
}
finally//最终要处理的事情
{
Console.WriteLine("既然都犯错了,那就收工吃饭吧!");
}
Console.ReadKey();
}
}
}
输入:
11
结果:
请输入1~10任一数
11
索引在阵列的界限之外。
既然都犯错了,那就收工吃饭吧!
<<: Day 16:把做好的 HTML 加入 Angular 吧!
>>: 前端工程师也能开发全端网页:挑战 30 天用 React 加上 Firebase 打造社群网站|Day28 留言电子邮件通知
前言 提到JDK就不得不提到JRE了,先来介绍他们之间的差别吧。 JRE:Java Runtime ...
哈罗, 我们在前面几天学习了以下这些主题: 资讯蒐集(Footprinting) 网路扫描(Scan...
接下来,开始看看如何着手进行 Vue 的开发吧 这边都是透过最原始、最简单的网页开发模式进行,所以不...
大家中秋节快乐 有没有烧肉吃饱饱,剥柚子,带柚子帽呢? 今天正15,月亮超级圆好漂亮喔 今天是我们来...
接着进入一个全新的篇章,介绍一下资料库。其中资料分析基础能力之一是可以从资料库拿取资料,因此我们需要...