soo*_*ise 9 c# class-design try-catch
我已经使用try和catch语句作为一种简单的方法来保持我的代码运行而不会崩溃(我会把所有内容都包装好).最近,我想开始更正确地使用try和catch语句.这里作为一个例子我有疑问:
public class Ninja{
Ninja(){
}
public void ThrowShirikin(int numberOfShirikins){
try{
if(numberOfShirikins == 0){
throw new System.ArgumentException("Invalid number of shirikins");
}
//Throw shirikin
}
catch(ArgumentException e){
MessageBox.Show(e.Message);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的Ninja类中,我的ThrowShirikin方法的全部内容都包含在try循环中.由于输入错误只有一次机会(在这种情况下,当numberOfShirikins == 0时),不仅应该检查这个代码行包含在try循环中吗?见下文:
public class Ninja{
Ninja(){
}
public void ThrowShirikin(int numberOfShirikins){
bool errorsExist = false;
try{
if(numberOfShirikins == 0){
errorsExist = true;
throw new System.ArgumentException("Invalid number of shirikins");
}
}
catch(ArgumentException e){
MessageBox.Show(e.Message);
}
if(!errorsExist){
//Throw shirikin
}
}
}
Run Code Online (Sandbox Code Playgroud)
^但我在这里看起来有点笨重.关于我如何理解try catch语句的使用的任何建议和意见?谢谢!
编辑:
或者我可以这样做,所以//如果numberOfShirikins的值无效,则抛出shirikin代码永远不会执行?:
public class Ninja{
Ninja(){
}
public void ThrowShirikin(int numberOfShirikins){
try{
if(numberOfShirikins == 0){
throw new System.ArgumentException("Invalid number of shirikins");
return;
}
}
catch(ArgumentException e){
MessageBox.Show(e.Message);
}
//Throw shirikin
}
}
Run Code Online (Sandbox Code Playgroud)
它看起来像是try/catch唯一的存在来捕获您选择创建和抛出的异常,然后您捕获它只是为了向用户弹出消息框。然后您根据错误情况选择继续或不继续。
消除try和catch。消除消息框。请针对无效参数抛出异常。让函数的调用者决定是否要捕获以及如何处理。除了确定什么是有效的、什么是无效的之外,你的Ninja班级不应该做出这些决定。
if (numberOfShirikins == 0)
throw new ArgumentException("...");
// rest of your shirikin throwing code
Run Code Online (Sandbox Code Playgroud)