文章目录
一、请简述Exception 的作用定义和使用场景
定义:程序中的运行时错误,它违反一个系统约束或应用程序约束,或出现了在正常操作时未预料的情形。
使用场景:分为系统异常和自定义异常。常见的系统异常有:ArithmeticException(算数异常),NullReferenceException(空引用异常),IndexOutOfRangeException(索引越界异常),InvalidOperationException(无效操作异常)等。异常处理包括:try-catch块,finally块,throw关键字以及使用using语句处理资源。
二、异常捕获练习
题目 1: 除法计算器
编写一个程序,读取两个整数并进行除法运算。如果除数为零,程序应捕获 DivideByZeroException 异常,并输出适当的错误消息。
要求:
用户输入两个整数。
捕获除零异常,并输出错误信息。
using System; using System.Diagnostics; using System.Drawing; namespace ConsoleApp1 { public class Program { static void Main(string[] args) { string x=Console.ReadLine(); string y=Console.ReadLine(); int a=Convert.ToInt32(x); int b=Convert.ToInt32(y); compute(a,b); Console.ReadKey(); } public static void compute(int x, int y) { try { if(y==0) { x /= y; } } catch(System.DivideByZeroException ex) { Console.WriteLine(ex.Message); } } } }
题目 2: 文件读取
编写一个程序,尝试从指定文件中读取内容。如果文件不存在或路径无效,程序应捕获 FileNotFoundException 异常,并输出适当的错误消息。
要求:
使用 System.IO 命名空间中的 FileNotFoundException 异常。
捕获文件未找到异常,并输出错误信息。
using System; using System.Diagnostics; using System.Drawing; using System.IO; using System.Text; namespace ConsoleApp1 { public class Program { static void Main(string[] args) { Read(); Console.ReadKey(); } public static void Read() { try { FileStream file = new FileStream("C:\\test.txt", FileMode.Open); file.Close(); } catch(System.IO.FileNotFoundException ex) { Console.WriteLine(ex.Message); } } } }
题目 3: 数字转换
编写一个程序,尝试将用户输入的字符串转换为整数。如果输入的字符串不是有效的数字,程序应捕获 FormatException 异常,并输出适当的错误消息。
要求:
用户输入一个字符串。
尝试将其转换为整数。
捕获格式异常,并输出错误信息。
using System; using System.Diagnostics; using System.Drawing; using System.IO; using System.Text; namespace ConsoleApp1 { public class Program { static void Main(string[] args) { string a=Console.ReadLine(); string b=Console.ReadLine(); Change(a,b); Console.ReadKey(); } public static void Change(string a,string b) { try { int x = Convert.ToInt32(a); int y = Convert.ToInt32(b); } catch(System.FormatException ex) { Console.WriteLine(ex.Message); } } } }
题目 4: 数组访问
编写一个程序,尝试访问数组中的一个元素。如果索引超出数组的范围,程序应捕获 IndexOutOfRangeException 异常,并输出适当的错误消息。
要求:
创建一个整数数组。
用户输入一个索引。
捕获数组索引越界异常,并输出错误信息。
using System; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.IO; using System.Text; namespace ConsoleApp1 { public class Program { static void Main(string[] args) { Read(); Console.ReadKey(); } public static void Read() { int[] nums = new int[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; try { int x = nums[11]; } catch(System.IndexOutOfRangeException ex) { Console.WriteLine(ex.Message); } } } }
题目 5: 自定义异常
定义一个自定义异常类 InvalidAgeException,继承Exception,用来表示用户输入的年龄不合法(小于0或大于150)。编写一个程序,使用 InvalidAgeException 捕获这种非法年龄输入的异常,并输出适当的错误消息。
要求:
定义 InvalidAgeException 类。
用户输入年龄,检查是否合法,并使用自定义异常进行捕获。
using System; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.IO; using System.Text; namespace ConsoleApp1 { public class Program { static void Main(string[] args) { string a = Console.ReadLine(); int n=Convert.ToInt32(a); Age(n); Console.ReadKey(); } public static void Age(int n) { if (n < 0 || n > 150) { throw new InvalidAgeException("年龄不合法"); } } } } public class InvalidAgeException : System.Exception { public InvalidAgeException() { } public InvalidAgeException(string message) : base(message) { } public InvalidAgeException(string message,object invalidObject) : base(message) { } }
三、使用C#实现建造者模式,并说明其模式的适用场景
using System; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.IO; using System.Text; namespace ConsoleApp1 { public class Actor { public string Name { get; set; } public int Age { get; set; } public string Sex { get; set; } } public interface IActorBuider { Actor Product { get; set; } void CreateName(); void CreateAge(); void CreateSex(); Actor ReturnResult(); } public class AngleBuilder : IActorBuider { private Actor _product; public Actor Product { get { if (_product == null) { _product = new Actor(); } return _product; } set => _product = value; } public void CreateName() { Product.Name = "天使"; } public void CreateAge() { Product.Age = 20; } public void CreateSex() { Product.Sex = "女"; } public Actor ReturnResult() { return Product; } } public class ActorDirector { private IActorBuider _builder; public void SetBuilder(IActorBuider builder) { _builder = builder; } public Actor Constructor() { _builder.CreateName(); _builder.CreateAge(); _builder.CreateSex(); return _builder.ReturnResult(); } } public class Program { static void Main(string[] args) { ActorDirector ad= new ActorDirector(); ad.SetBuilder(new AngleBuilder()); Actor actor=ad.Constructor(); Console.WriteLine($"名称为:{actor.Name}"); Console.WriteLine($"年龄为:{actor.Age}"); Console.WriteLine($"性别为:{actor.Sex}"); } } }
四、使用C#实现原型模式,并说明其模式的适用场景
using System; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.IO; using System.Text; namespace ConsoleApp1 { public abstract class Prototype { public abstract void Fight(); public abstract void BegAlms(); public abstract Prototype Clone(); } public sealed class XingZheSunPrototype : Prototype { public override void Fight() { Console.WriteLine("腾云驾雾,各种武艺"); } public override void BegAlms() { Console.WriteLine("什么都能要来"); } public override Prototype Clone() { return (XingZheSunPrototype)this.MemberwiseClone(); } } public sealed class SunXingZhePrototype : Prototype { public override void Fight() { Console.WriteLine("七十二变"); } public override void BegAlms() { Console.WriteLine("只能要来水果"); } public override Prototype Clone() { return (SunXingZhePrototype)this.MemberwiseClone(); } } public class Program { static void Main(string[] args) { Prototype xingzhesun=new XingZheSunPrototype(); Prototype xingzhesun2=xingzhesun.Clone(); Prototype xingzhesun3= xingzhesun.Clone(); Prototype sunxingzhe=new SunXingZhePrototype(); Prototype sunxingzhe2=sunxingzhe.Clone(); Prototype sunxingzhe3= sunxingzhe.Clone(); Prototype sunxingzhe4= sunxingzhe.Clone(); Prototype sunxingzhe5= sunxingzhe.Clone(); sunxingzhe2.Fight(); xingzhesun3.BegAlms(); Console.Read(); } } }
五、使用C#实现适配器模式,并说明其模式的适用场景
using System; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.IO; using System.Text; namespace ConsoleApp1 { public class TwoHoleTarget { public virtual void Request() { Console.WriteLine("两孔的充电器可以使用"); } } public class ThreeHoleAdaptee { public void SpecificRequest() { Console.WriteLine("我是三个孔的插头也可以使用了"); } } public interface ITwoHoleTarget { void Request(); } public class threeToTwoAdapter : ThreeHoleAdaptee, ITwoHoleTarget { public void Request() { this.SpecificRequest(); } } public class ThreeToTwoAdapter : TwoHoleTarget { private ThreeHoleAdaptee threeHoleAdaptee = new ThreeHoleAdaptee(); public override void Request() { threeHoleAdaptee.SpecificRequest(); } } public class Program { static void Main(string[] args) { TwoHoleTarget homeTwoHole = new ThreeToTwoAdapter(); homeTwoHole.Request(); ITwoHoleTarget change = new threeToTwoAdapter(); change.Request(); Console.ReadLine(); } } }
六、使用C#实现桥接模式,并说明其模式的适用场景
using ConsoleApp1; using System; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.IO; using System.Security.Cryptography.X509Certificates; using System.Text; namespace ConsoleApp1 { public abstract class Database { protected PlatformImplementor _implementor; protected Database(PlatformImplementor implementor) { this._implementor = implementor; } public abstract void Create(); } public abstract class PlatformImplementor { public abstract void Process(); } public class SqlServer2000 : Database { public SqlServer2000(PlatformImplementor implementor) : base(implementor){ } public override void Create() { this._implementor.Process(); } } } public class SqlServer2005 : Database { public SqlServer2005(PlatformImplementor implementor) : base(implementor){ } public override void Create() { this._implementor.Process(); } } public class SqlServer2000UnixImplementor : PlatformImplementor { public override void Process() { Console.WriteLine("SqlServer2000针对Unix的具体实现"); } } public sealed class SqlServer2005UnixImplementor : PlatformImplementor { public override void Process() { Console.WriteLine("SqlServer2005针对Unix的具体实现"); } } public class Program { static void Main(string[] args) { PlatformImplementor SqlServer2000UnixImp = new SqlServer2000UnixImplementor(); PlatformImplementor SqlServer2005UnixImp = new SqlServer2005UnixImplementor(); Database SqlServer2000Unix = new SqlServer2000(SqlServer2000UnixImp); Database SqlServer2005Unix = new SqlServer2005(SqlServer2005UnixImp); SqlServer2000Unix.Create(); SqlServer2005Unix.Create(); Console.ReadLine(); } }
七、使用C#实现装饰器模式,并说明其模式的适用场景
using ConsoleApp1; using System; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.IO; using System.Security.Cryptography.X509Certificates; using System.Text; namespace ConsoleApp1 { public abstract class House { public abstract void Renuvation(); } public abstract class DecorationStrategy : House { protected House _house; protected DecorationStrategy(House house) { this._house = house; } public override void Renuvation() { if (this._house != null) { this._house.Renuvation(); } } } public sealed class StarDengHouse : House { public override void Renuvation() { Console.WriteLine("装修StarDeng的房子"); } } public sealed class HouseSecurityDecorator : DecorationStrategy { public HouseSecurityDecorator(House house) : base(house) { } public override void Renuvation() { base.Renuvation(); Console.WriteLine("增加安全系统"); } } public sealed class KeepWarmDecorator : DecorationStrategy { public KeepWarmDecorator(House house) : base(house) { } public override void Renuvation() { base.Renuvation(); Console.WriteLine("增加了保温的功能"); } } public class Program { static void Main(string[] args) { House myselfHouse = new StarDengHouse(); DecorationStrategy securityHouse = new HouseSecurityDecorator(myselfHouse); securityHouse.Renuvation(); DecorationStrategy securityAndWarmHouse = new KeepWarmDecorator(securityHouse); securityAndWarmHouse.Renuvation(); Console.ReadLine(); } } }
八、使用C#实现外观模式,并说明其模式的适用场景
using ConsoleApp1; using System; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.IO; using System.Security.Cryptography.X509Certificates; using System.Text; namespace ConsoleApp1 { public class SystemA { public void MethodA() { Console.WriteLine("执行身份认证"); } } public class SystemB { public void MethodB() { Console.WriteLine("执行系统安全检查"); } } public class SystemC { public void MethodC() { Console.WriteLine("执行网银安全检查"); } } public class SystemFacade { private SystemA auth; private SystemB security; private SystemC netbank; public SystemFacade() { auth = new SystemA(); security = new SystemB(); netbank = new SystemC(); } public void Buy() { auth.MethodA(); security.MethodB(); netbank.MethodC(); Console.WriteLine("我已经成功购买了"); } } public class Program { static void Main(string[] args) { SystemFacade facade = new SystemFacade(); facade.Buy(); Console.ReadKey(); } } }