C#第八周异常处理
2016-04-23 17:29
411 查看
1 将百分制转换为五分制,如果输入的百分制成绩超出0-100时,程序抛出异常。
提示:定义一个用户自定义异常类OverflowRange,通过Throw new OverflowRange(message)实现。
2 编写一个计算阶乘的程序,当输入的数据是小数时引发异常。
提示:定义一个用户自定义异常类。
提示:定义一个用户自定义异常类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(); } } }
相关文章推荐
- C#反射,特性结合使用
- c# sftp 库 ssh.net, sharpssh
- c# sftp 库 Chilkat
- C# 中英文与Unicode之间的相互装换
- 【C#】System.IO.Stream 中flush的用法
- C#正则表达式
- C# 中的委托和事件
- C# DES (ECB模式) 加密解密 --单倍长
- z铭 WPF bitmap转bitmapimage 使用 CreateBitmapSourceFromHBitmap内存泄漏
- C# 如何获取出错的错误所在行数信息[原创]_C#教程_脚本之家
- C# 中堆与栈的浅记
- 新闻发布系统——静态方法使用问题(Static)
- C# Hello World WinForm
- 第四章:流程控制
- C# Hello World
- C#二叉树简易实例
- C# ASCII码排序
- C#中Directory.GetFiles() 函数的使用
- 进程(应用程序)之一
- C#OOP之二 变量和表达式