Is it good practice to catch all exceptions and throw them as a special type of exception in terms of classification?

It’s good practice to catch all exceptions and throw them as a special type - as a rule, classify all exceptions thrown from a certain part (or service) of an application?

Sort of:

//  This class is used to label all the exceptions occured on 
// Race Cars Service calls as RaceCarsServiceException
public class RaceCarsServiceException : Exception
{

 public class RaceCarsServiceException (Exception e) 
               : base("Something went wrong!", e)
  {
     // Basically I assign the exception e as the inner exception 
     //by using the constructor method of Exception class
  }

}

public class RaceCarsService
{

// Some member fields, methods etc. here

 public double GetMaxSpeed(CarModel model)
 {
   try 
     {
       return (double)_carsWebService.GetMaxSpeed(model.ToString());
     }

   catch(Exception e)
     {
       throw new RaceCarsServiceException(e); // So all exceptions are rethrown 
                                           //as type of RaceCarsServiceException
     }
 }
}
+3
source share
3 answers

This is one of those huge questions that ask questions.

, expcetion, . - , , .

, , .

fo rinstance , , , , , .

. , , .

, , , , , , , ( , ).

, , - . , , .

, , , RecordDoesNotExist DAL, -.

, , . .

. , , .

.

EDIT: , .

.NET

-

-

+2

, .

.

+1

( , ). , , , , .

try
{
    AMethodMayThrowExceptions();
}
catch (FileNotFoundException fileEx)
{
      //maybe create the file and retry
}
catch (TimeoutException timeoutEx)
{
      //maybe a retry after n seconds
}
catch (Exception ex)
{ 
      //other exceptions which I don't care
      //just a prompt of ex.Message or something
}

, RaceCarsServiceException?

catch (RaceCarsServiceException ex)
{
    // now it supposed to have a `ErrorCode` property, or an inner exception
    if (ex.ErrorCode == ErrorCode.File)
        //file exception, everything is the same with FileNotFoundException
    else ...
}

, !

0

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


All Articles