TrN*_*TrN 20 c# exception-handling exception
嗨,我想问,因为我不确定它是否是使用异常的私人:
public int Method(int a, int b) {
if(a<b) throw new ArgumentException("the first argument cannot be less than the second");
//do stuff...
}
Run Code Online (Sandbox Code Playgroud)
if语句之后可以抛出Exception吗?或者我应该总是使用try-catch与异常一起使用?
Fil*_*erg 25
这完全有效.这正是用于检查逻辑中的"例外"的异常,这些事情本来就不是假设的.
捕获异常的想法是,当您在某处传递数据并对其进行处理时,您可能并不总是知道结果是否有效,即您想捕获的时间.
关于你的方法,Method当你调用它时,你不想捕获内部而是实际上,这是一个例子:
try
{
var a = 10;
var b = 100;
var result = Method(a, b);
}
catch(ArgumentException ex)
{
// Report this back to the user interface in a nice way
}
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,a小于b,所以你可以在这里得到一个例外,你可以相应地处理它.
这是完全有效的,即使使用构造函数也可以使用相同的构造.但你不应该做的是
public int Method(int a, int b)
{
try
{
if (a < b)
throw new ArgumentException("the first argument cannot be less than the second");
}
catch (Exception)
{
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27919 次 |
| 最近记录: |