[英]How Can I Force Execution to the Catch Block?
I am wondering can try..catch
force execution to go into the catch
and run code in there?我想知道可以
try..catch
强制执行进入catch
并在那里运行代码吗?
here example code:这里示例代码:
try {
if (AnyConditionTrue) {
// run some code
}
else {
// go catch
}
} catch (Exception) {
// run some code here...
}
Rather than throwing an Exception in the else
, I would recommend extracting the code from your catch
into a method and call that from your else与其在
else
抛出异常,我建议您将catch
的代码提取到一个方法中,然后从 else 中调用它
try
{
if (AnyConditionTrue)
{
MethodWhenTrue();
}
else
{
HandleError();
}
}
catch(Exception ex)
{
HandleError();
}
try{
if (AnyConditionTrue){
//run some code
}
else{
throw new Exception();
}
}
catch(){
//run some code here...
}
But like Yuck has stated, I wouldn't recommend this.但就像 Yuck 所说的,我不推荐这个。 You should take a step back at your design and what you're looking to accomplish.
您应该退后一步,了解您的设计以及您希望实现的目标。 There's a better way to do it (ie with normal conditional flow, instead of exception handling).
有一个更好的方法来做到这一点(即使用正常的条件流,而不是异常处理)。
Yes, you have to throw exception :是的,你必须抛出异常:
try
{
throw new Exception("hello");
}
catch (Exception)
{
//run some code here...
}
An effective way to throw an Exception
and also jump to Catch
as so:一种抛出
Exception
并跳转到Catch
的有效方法,如下所示:
try
{
throw new Exception("Exception Message");
}
catch (Exception e)
{
// after the throw, you will land here
}
if(conditiontrue)
{
}
else{
throw new Exception();
}
As cadrel said, but pass through an Exception to provide more feedback, which will be shown in the innerException:正如cadrel所说,但是通过一个Exception来提供更多的反馈,会在innerException中显示:
try
{
if (AnyConditionTrue)
{
MethodWhenTrue();
}
else
{
HandleError(new Exception("AnyCondition is not true"));
}
}
catch (Exception ex)
{
HandleError(ex);
}
... ...
private void HandleError(Exception ex) {
throw new ApplicationException("Failure!", ex);
}
If you want to "force" a try catch, just purposely do something stupid, like this: 如果你想“强迫”尝试捕获,只是故意做一些愚蠢的事情,像这样:
List<string> cc = null;
foreach (string c in cc) {}
public class CustomException: Exception
{
public CustomException(string message)
: base(message) { }
}
// //
if(something == anything)
{
throw new CustomException(" custom text message");
}
you can try this你可以试试这个
Yes, if you throw
the exception that you intend to catch
from within the try, it will be caught in the catch section.是的,如果您
throw
您打算从 try 中catch
的异常,它将在 catch 部分中捕获。
I have to ask you why you would want to do this though?我不得不问你为什么要这样做? Exception handling is not meant to be a substitute for control flow.
异常处理并不意味着要替代控制流。
I think what you want is a finally
block: http://msdn.microsoft.com/en-us/library/zwc8s4fz(v=vs.80).aspx我认为你想要的是一个
finally
块: http : //msdn.microsoft.com/en-us/library/zwc8s4fz(v=vs.80).aspx
see this看到这个
try
{
doSomething();
}
catch
{
catchSomething();
throw an error
}
finally
{
alwaysDoThis();
}
This is different if/when you do this:如果/当您这样做时,情况会有所不同:
try
{
doSomething();
}
catch
{
catchSomething();
throw an error
}
alwaysDoThis();// will not run on error (in the catch) condition
the the this last instance, if an error occurs, the catch will execute but NOT the alwaysDoThis();
最后一个实例,如果发生错误,catch 将执行,但不是
alwaysDoThis();
. . Of course you can still have multiple
catch
as always.当然,您仍然可以像往常一样进行多次
catch
。
Slight resurrection, but I wanted to add both a sample (primarily like others) and a use case.轻微的复活,但我想添加一个样本(主要像其他人一样)和一个用例。
public int GetValueNum(string name)
{
int _ret = 0;
try
{
Control c = (extendedControls.Single(s => s.ValueName == name) as Control);
if (c.GetType() == typeof(ExtendedNumericUpDown))
_ret = (int)((ExtendedNumericUpDown)c).Value;
else
throw new Exception();
}
catch
{
throw new InvalidCastException(String.Format("Invalid cast fetching .Value value for {0}.\nExtendedControllerListener.GetValueNum()", name));
}
return _ret;
}
In my case, I have custom controls - a handful of controls that use a base Windows.Forms control, but add two bools and a string for tracking, and also automatically get registered to a Singleton List<T>
so they can be properly fetched without drilling down through control containers (it's a tabbed form).就我而言,我有自定义控件 - 一些使用基本 Windows.Forms 控件的控件,但添加了两个布尔值和一个用于跟踪的字符串,并且还自动注册到 Singleton
List<T>
以便可以正确获取它们无需深入控制容器(它是选项卡形式)。
In this case, I'm creating some methods to easily get values ( .Value, .Text, .Checked, .Enabled
) by a name string.在这种情况下,我创建了一些方法来通过名称字符串轻松获取值(
.Value, .Text, .Checked, .Enabled
)。 In the case of .Value
, not all Control
objects have it.在
.Value
的情况下,并非所有Control
对象都有它。 If the extended control is not of type ExtendedNumericUpDown
, it IS an InvalidCastException
as the method should not be called against that type of control.如果扩展控件的类型不是
ExtendedNumericUpDown
,则它是InvalidCastException
因为不应针对该类型的控件调用该方法。 This isn't flow, but the prescribed usage of invalid cast.这不是流,而是无效转换的规定用法。 Since
Control
doesn't naturally have a .Value
property, Visual Studio won't let me just force an attempt and fail after.由于
Control
自然没有.Value
属性,Visual Studio 不会让我只是强制尝试并在之后失败。
您可以抛出异常以强制捕获
throw new Exception(...);
why are you catching an exception?你为什么要捕捉异常? Why not just run the code in your "else" block?
为什么不直接在“else”块中运行代码? If you MUST do it that way, just throw a new exception
如果你必须这样做,就抛出一个新的异常
throw new Exception();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.