您的位置:首页 > 编程语言 > C#

C#第八周异常处理

2016-04-23 17:29 411 查看
1      将百分制转换为五分制,如果输入的百分制成绩超出0-100时,程序抛出异常。

      提示:定义一个用户自定义异常类OverflowRange,通过Throw new  OverflowRange(message)实现。

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

namespace ConsoleApplication1
{
class OverflowRange : ApplicationException
{
public OverflowRange(string msg) : base(msg) { }
}

class Program
{
static void Main(string[] args)
{
try
{
Console.Write("请输入百分制分数:");
int g = int.Parse(Console.ReadLine());
if (g < 0 || g > 100)
throw new OverflowRange("超出范围!");
Console.WriteLine(parse(g));
}
catch (OverflowRange e)
{
Console.WriteLine(e.Message);
}
finally
{
Console.WriteLine("按任意键退出....");
Console.ReadLine();

}
Console.ReadKey();
}
public static char parse(int g)
{
if (g > 80) return 'A';
else if (g > 60) return 'B';
else if (g > 40) return 'C';
else if (g > 20) return 'D';
else return 'E';
}
}
}

2  编写一个计算阶乘的程序,当输入的数据是小数时引发异常。

    提示:定义一个用户自定义异常类。

using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace getnum
{
class outoException : ApplicationException
{
public outoException(string msg)
: base(msg)
{ }
}
class Program
{
public static Boolean d(string s)
{
Regex rex = new Regex(@"\d*[.]\d*");
if (rex.IsMatch(s))
return true;
return false;
}
static void Main(string[] args)
{
try
{
Console.Write("请输入一个整数:");
string n = Console.ReadLine();
if (d(n))
throw new outoException("不允许是小数.");
int s = int.Parse(n);
int t = s;
while (s-->1)
{
t = t * s;
}
Console.WriteLine("{0}!= {1}", int.Parse(n), t);
}
catch (outoException e)
{
Console.WriteLine(e.Message);
}
finally
{
Console.WriteLine("按任意键退出....");
}
Console.ReadKey();
}
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: