简体   繁体   中英

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?

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

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. 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:

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:

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.

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

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(); . Of course you can still have multiple catch as always.

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).

In this case, I'm creating some methods to easily get values ( .Value, .Text, .Checked, .Enabled ) by a name string. In the case of .Value , not all Control objects have it. 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. 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.

您可以抛出异常以强制捕获

throw new Exception(...);

why are you catching an exception? Why not just run the code in your "else" block? If you MUST do it that way, just throw a new exception

throw new Exception();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM