以下是解释我的问题的代码示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
try
{
Program.Sample();
Console.ReadLine();
}
catch (Exception)
{
Console.WriteLine("InvalidOperation Exception");
}
}
static bool Sample()
{
int a = 1; int b = 2;
if (a == b) //Some Condition checking
{
return true;
}
else
{ //Is this Proper returning Exception In Boolean method instead of False
throw new InvalidOperationException();
}
}
}
}
我在客户端应用程序中捕获此异常并显示消息我想知道这是否是正确的方法?
答案 0 :(得分:5)
异常情况发生或遇到使用错误时应抛出异常,即null参数在您的情况下,最好只返回false
。
答案 1 :(得分:0)
如果可能,请不要将异常用于正常的控制流程。除了系统故障和具有潜在竞争条件的操作之外,框架设计者应该设计API,以便用户可以编写不会抛出异常的代码。例如,您可以在调用成员之前提供检查前提条件的方法,以便用户可以编写不会抛出异常的代码。
考虑通过调用System.Environment.FailFast(System.String)(.NET Framework 2.0版功能)来终止进程,而不是抛出异常,如果您的代码遇到继续执行不安全的情况。