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 给新生的简短祝福语