When to handle an exception?

I am writing an application that I can combine tasks with several steps. I have code similar to the one below and I want to know if this is the usual way to handle exceptions. This code will probably never be noticed by anyone, but it may be so, so I would like to know that I am handling exceptions as expected.

IEnumerable<Task> Tasks;

foreach(var task in Tasks)
{
 try
 {
   //boiler plate prep for task (loading libraries, connecting, logging start, etc)

   foreach(var step in task.Steps)
   {  
      try
      {
        step.Execute();
      }
      catch(Exception ex)
      {
        LogStepError(step, ex);
        throw;
      }
    }

    //Notify parties task has been completed successfully, log task completion
  }
  catch(Exception ex)
  {
      LogTaskFailure(task);
  }
  finally
  {
    //close connections, etc
  }
}



interface ITaskStep
{
    void Execute()
    {

    }            
}

I also wanted to add that the execution steps implement the ITaskStep interface, so the Execute implementation is not my own (well, in this case, but someone can implement the interface). My code just loads the library and runs any ITasks and their ITaskSteps.

+3
source share
6 answers

, . , , , , , . .

TaskIsBogusException PrinterOnFireException : . - , , PrinterOnFireException , golly .

, , , . (, , , , ) .

+7

step.Execute() - , for, : ( )

IEnumerable<Task> Tasks;

foreach(var task in Tasks)
{
   try
   {
     //boiler plate prep for task
   }
   catch(Exception ex)
   {
     LogTaskFailure(task);
     continue;
   }
   foreach(var step in task.Steps)
   {  
      try
      {
        step.Execute();
      }
      catch(Exception ex)
      {
        LogStepError(step, ex);
        LogTaskFailure(task);
        break;
      }
    }
}

class TaskStep
{
    private void Execute()
    {
       //do some stuff, don't catch any exceptions
    }            
}

.

+2

, , , , , , .

, . , , , , , , . , , .

:



try
{
     //Your stuff
}
catch(DivideByZeroException ex)
{
   //Could you manage this?
}
catch(NullReferenceException ex)
{
   //Could you manage this one?
}
catch(IOException ex)
{
      //What about this one?
}
finally
{
      //Any cleanup code
}

+2

- , , , . , , , , , .

, .

0

, , , , .

foreach(var step in task.Steps)
       {  
          try
          {
            step.Execute();
          }
          catch(Exception ex)
          {
            LogStepError(step, ex);
            LogTaskFailure(task);
            break;
          }
        }
0

, varibale Exception , .

:

try{
foreach(var step in task.Steps)
       {  
            if(!step.Execute()){
                break;
            }

        }
}catch(Exception ex)
{
}
0

Source: https://habr.com/ru/post/1713367/


All Articles