[英]Is it possible to use a method throwing an exception in an if statement condition? c#
所以我试图错误处理我的代码,到目前为止,这就是我所拥有的:
date = GetDate();
if(date.throws_exception())
{
// would it be possible to make a condition for where you can say if date throws exception?
}
string GetDate()
{
try
{
.
.
.
return date;
}
catch(Exception ex)
{
throw new Exception();
}
}
我想知道的是 if 条件是可能的,你能说:
if(date throws exception)
您可以将方法调用放在 try catch 块中,或重写您的方法以返回结果 object,或指示成功并保存值的元组。
示例返回表示成功的元组:
(bool Success, string Value) GetDate()
{
try
{
.
.
.
return (true, date);
}
catch(Exception ex)
{
return (false, null);
}
}
像这样使用:
var result = GetDate();
if (result.Success)
{
// do something with result.Value
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.