使用示例在 C# 中自定義異常
異常是在程式執行期間出現的問題。C# 異常是對程式執行時出現的異常情況的響應,例如嘗試除以零。
定義自己的異常。使用者自定義的異常類派生自 Exception 類。
以下是一個示例 −
示例
using System;
namespace UserDefinedException {
class TestFitness {
static void Main(string[] args) {
Fitness f = new Fitness();
try {
f.showResult();
} catch(FitnessTestFailedException e) {
Console.WriteLine("User defined exception: {0}", e.Message);
}
Console.ReadKey();
}
}
}
public class FitnessTestFailedException: Exception {
public FitnessTestFailedException(string message): base(message) {
}
}
public class Fitness {
int points = 0;
public void showResult() {
if(points < 110) {
throw (new FitnessTestFailedException("Player failed the fitness test!"));
} else {
Console.WriteLine("Player passed the fitness test!");
}
}
}以上,我們建立了一個使用者自定義的異常 −
public class FitnessTestFailedException: Exception {
public FitnessTestFailedException(string message): base(message) {
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP