问题及代码:
//*
//* Copyright (c) 2014, 烟台大学计算机学院
//* All rights reserved.
//* 文件名称:test.cpp
//* 作 者:宋健
//* 完成日期:2016年 4月 22日
//* 版 本 号:v1.0
//*
//* 问题描述:将百分制转换为五分制,如果输入的百分制成绩超出0-100时,程序抛出异常
//
//* 程序输入:分数
//* 程序输出:转换分数
//*
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
{
double score, s;
Console.WriteLine("请输入百分制成绩:");
score = double.Parse(Console.ReadLine());
if (score > 100 || score < 0)
{
throw new OverflowRange("请输入0-100之内的数!!!");
}
s = score / 100 * 5;
Console.WriteLine("五分制成绩为{0}", s);
Console.ReadKey();
}
catch (OverflowRange e)
{
Console.WriteLine(e.Message);
Console.ReadKey();
}
catch (FormatException)
{
Console.WriteLine("必须输入数字!!!");
Console.ReadKey();
}
}
}
}
运行结果:
知识点总结:
在异常抛出时要考虑清楚异常的特点,同时要多熟练抛出异常这种方法