在软件开发中,异常处理是一种用于捕获和处理运行时错误的机制。通过异常处理,程序可以在遇到不可预见的问题时继续运行或进行适当的资源清理。
基础知识
异常的概念
- 异常是在程序执行过程中发生的错误,可以是系统级别或者应用级别的。
- 常见异常包括DivideByZeroException、NullReferenceException、IndexOutOfRangeException等。
基本语法
try-catch 结构
try-catch块用于捕获和处理异常。
try
{
int divisor = 0;
int result = 10 / divisor;
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Cannot divide by zero!");
}
多个catch块
可以根据不同的异常类型设置多个catch块。
try
{
// 可能抛出多种异常的代码
}
catch (NullReferenceException ex)
{
Console.WriteLine("Object reference not set to an instance of an object.");
}
catch (Exception ex) // 捕获所有其他类型的异常
{
Console.WriteLine("An error occurred: " + ex.Message);
}
finally块
finally块中的代码总会执行,用于释放资源。
try
{
// 可能抛出异常的代码
}
catch (Exception ex)
{
Console.WriteLine("Exception caught");
}
finally
{
Console.WriteLine("Cleanup code here");
}
抛出异常
使用throw关键字显式抛出异常
public void ProcessData(int value)
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value), "Value cannot be negative");
}
// 处理数据
}
自定义异常
创建自定义异常类以处理特定情况。
public class InvalidAgeException : Exception
{
public InvalidAgeException(string message) : base(message)
{
}
}
使用自定义异常:
public void RegisterUser(string name, int age)
{
if (age < 18)
{
throw new InvalidAgeException("User must be at least 18 years old");
}
// 注册用户逻辑
}
实践习题
1.基本异常处理
编写一个程序,要求用户输入两个整数,然后输出它们的商。对除零操作进行适当的异常处理。
using System;
public class DivisionExample
{
public static void Main(string[] args)
{
try
{
Console.WriteLine("请输入第一个整数:");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("请输入第二个整数:");
int num2 = Convert.ToInt32(Console.ReadLine());
int result = num1 / num2;
Console.WriteLine($"结果是:{result}");
}
catch (DivideByZeroException ex)
{
Console.WriteLine("错误:不能除以零!");
}
catch (FormatException ex)
{
Console.WriteLine("错误:请输入有效的整数!");
}
finally
{
Console.WriteLine("运算结束。");
}
}
}
2.自定义异常
创建一个自定义异常,用于处理银行账户取款操作,防止透支。
public class InsufficientFundsException : Exception
{
public InsufficientFundsException(string message) : base(message)
{
}
}
public class BankAccount
{
public decimal Balance { get; private set; }
public BankAccount(decimal initialBalance)
{
Balance = initialBalance;
}
public void Withdraw(decimal amount)
{
if (amount > Balance)
{
throw new InsufficientFundsException("余额不足,无法完成取款。");
}
Balance -= amount;
Console.WriteLine($"取款成功。当前余额:{Balance}");
}
}
public class Program
{
public static void Main(string[] args)
{
BankAccount account = new BankAccount(100m);
try
{
account.Withdraw(150m);
}
catch (InsufficientFundsException ex)
{
Console.WriteLine(ex.Message);
}
}
}
3.综合应用
在文件读写操作中实现异常处理,确保无论是否成功读取文件,都能正确关闭文件资源。
using System;
using System.IO;
public class FileReadExample
{
public static void Main(string[] args)
{
StreamReader reader = null;
try
{
reader = new StreamReader("example.txt");
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
catch (FileNotFoundException ex)
{
Console.WriteLine("错误:找不到指定的文件。");
}
catch (IOException ex)
{
Console.WriteLine("错误:读取文件时发生错误。");
}
finally
{
if (reader != null)
{
reader.Close();
Console.WriteLine("文件已关闭。");
}
}
}
}
这些例子展示了如何在C#中使用异常处理机制来提高程序的稳健性和用户体验。如有其他问题或更多帮助,请随时告知我!