C#中用户定义的自定义异常
C#异常由类表示。C#中的异常类主要是直接或间接派生自System.Exception类。
您还可以定义自己的异常。用户定义的异常类派生自Exception类。
以下是一个例子-
示例
using System;
namespace UserDefinedException {
class TestTemperature {
static void Main(string[] args) {
Temperature temp = new Temperature();
try {
temp.showTemp();
} catch(TempIsZeroException e) {
Console.WriteLine("TempIsZeroException: {0}", e.Message);
}
Console.ReadKey();
}
}
}
public class TempIsZeroException: Exception {
public TempIsZeroException(string message): base(message) {
}
}
public class Temperature {
int temperature = 0;
public void showTemp() {
if(temperature == 0) {
throw (new TempIsZeroException("Zero Temperature found"));
} else {
Console.WriteLine("Temperature: {0}", temperature);
}
}
}热门推荐
10 读书祝福语女生短句简短
11 感谢同事新婚祝福语简短
12 感谢教官文案祝福语简短
13 员工聚会蛋糕祝福语简短
14 元宵发客户祝福语简短
15 给团队信心祝福语简短
16 医美的祝福语大全简短
17 异国姻缘的祝福语简短
18 兄妹拍照祝福语简短的话