我正在为任务分配井字游戏,我是C#的新手。对于错误动作,我有一个自定义例外,称为BadMoveException
,如果用户输入的数字不是0-8,那就是例外。有用于赋值的现有代码,我想知道是否应该删除代码以创建自己的代码来使用此异常,或者是否很容易在此处实现?这是代码:
string input;
int position;
do
{
input = Console.ReadLine();
}
while (!int.TryParse(input, out position));
我需要捕获BadMoveException
以及其他任何带有未知错误消息的消息。预先谢谢你!
答案 0 :(得分:0)
只要您的(* Physical Constants *)
k = 1.38 * 10^-23;
ε = 8.85 * 10^-12;
e = 1.6 *10^-19;
m0 = 9.11 * 10^-31;
h = 6.63 * 10^-34;
(* Basic information of Black Phosphorus *)
κ = 6.1;
me = 0.13 * m0;
mp = 0.28 * m0;
Eg = 0.33;
Δφ = -0.1;
(* Δφ = φTip - χ *)
ΔV = 0.04;
(* ΔV = EA - EV *)
(* Experimental conditions *)
T = 4.3;
ΔS = 0.4*10^-9;
(* Distance between tip and sample *)
ni = 2/h^3*(2*Pi*k*T)^(3/2)*(me*mp)^(3/4)*E^(-((Eg*e)/(2*k*T)));
uB = (e*φB)/(k*T);
NA = 10^22;
ND = 0;
X = FindRoot[-(NA/(1+4*E^(((ΔV-1/2 Eg-φB)*e)/(k*T))))==2*ni*Sinh[uB], {φB, 1/2 Eg}];
φB = φB /. X;
uB = (e*φB)/(k*T);
LD = ((κ*ε*k*T)/(2*e^2*ni))^(1/2);
Result = FindRoot[(k*T)/e*1/LD*(NA/ni*
Log[(1 + 1/2*E^((e*φS)/(k*T) - ((ΔV - 1/2*Eg)*e)/(k*T)))/
(1 + 1/2*E^((e*φB)/(k*T) - ((ΔV - 1/2*Eg)*e)/(k*T)))] -
1/Integrate[x^(1/2)/(1+E^((e*Eg)/(2*k*T)+x)), {x, 0, Infinity}]*
(2/3*Integrate[x^(3/2)/(1+E^((e*Eg)/(2*k*T)+x+(e*φB)/(k*T))), {x, 0, Infinity}] -
2/3*Integrate[x^(3/2)/(1+E^((e*Eg)/(2*k*T)+x+(e*φS)/(k*T))), {x, 0, Infinity}]) +
1/Integrate[x^(1/2)/(1+E^((e*Eg)/(2*k*T)+x)), {x, 0, Infinity}]*
(2/3*Integrate[x^(3/2)/(1+E^((e*Eg)/(2*k*T)+x-(e*φS)/(k*T))), {x, 0, Infinity}] -
2/3*Integrate[x^(3/2)/(1+E^((e*Eg)/(2*k*T)+x-(e*φB)/(k*T))), {x, 0, Infinity}]))^(1/2)*
(-ΔS) == Δφ - 1/2*Eg + φB - (φS - φB), {φS, -(1/2) Eg}];
φ = (φS /. Result[[1]]) - φB
(*-0.324431*)
继承自BadMoveException
,您就可以像使用其他Exception
一样使用它,如下所示:
Exception
此处提供了有关异常处理的更多信息:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/exceptions/
答案 1 :(得分:0)
这就是我所拥有的:
1-首先,您的异常需要像这样从Exception继承:
public class BadMoveException : Exception { // Your code here }
2-遇到错误时,您可以像这样使用它:
throw new BadMoveException(// Enter parameter if you have any in you class);
然后您抓住了它:
try
{
if(Position < 0 || Position > 8)
{
throw new BadMoveException(// Enter parameter here if you have any);
}
else
{
// Your code here
}
}
catch(BadMoveException bmex) { // Show message here }
catch(Exception ex) { // Show other exception }
希望有帮助!
文档链接:http://www.tutorialsteacher.com/csharp/custom-exception-csharp https://stackify.com/csharp-exception-handling-best-practices/