How Can I Force Execution to the Catch Block?

后端 未结 12 1221
野趣味
野趣味 2021-01-17 07:46

I am wondering can try..catch force execution to go into the catch and run code in there?

here example code:

try {
    if (         


        
相关标签:
12条回答
  • 2021-01-17 08:03
    public class CustomException: Exception
    {
         public CustomException(string message)
            : base(message) { }
    
    }
    

    //

    if(something == anything)
    {
       throw new CustomException(" custom text message");
    }
    

    you can try this

    0 讨论(0)
  • 2021-01-17 08:03

    You could throw an exception to force a catch

    throw new Exception(...);
    
    0 讨论(0)
  • 2021-01-17 08:07

    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);
    }
    
    0 讨论(0)
  • 2021-01-17 08:08

    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.

    0 讨论(0)
  • 2021-01-17 08:15
    if(conditiontrue)
    {
    
    }
    else{
        throw new Exception();
    }
    
    0 讨论(0)
  • 2021-01-17 08:15

    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.

    0 讨论(0)
提交回复
热议问题