[PHP] when to use Try Catch (rpm)

A few suggestions:
   If you can not handle an exception, do not catch it. 
   If you catch an exception, do not casually handle it. 
   Try to catch the exception in the near exception is thrown. 
   Where will it catch exceptions logged unless you intend to throw it back. 
   According to your exception handling must be more than fine to construct your method. 
   Need to use several types of abnormalities are several, especially abnormal for the application.
   The low-level high-level package into the programmer abnormal abnormality more readily understood.
   Try to complete the data output caused by abnormal
   try to catch the exception has a specific meaning: for example SqlException, rather than simply capturing a Exception.

  If your program is not demanding too much for efficiency, I suggest that you would rather use some abnormality is good.
Note: I mean more use of all trycatch not let you up, then catch (Exception e) all exceptions are masked; but do not consider the loss of efficiency trycatch may bring, and focus stability program sex.
As for how to optimize the use of trycatch, take your time. My personal use, the impact is not great in fact.

 

    

1. Do not abuse Try ... Catch. Generally required only on the outermost function. Exception because the function can not be thrown out again. Catch live accordingly it is necessary to process, display Error Message. Or converted into a good agreement with the calling module Error Code. Catch live inside a function, even if the Exception, but also throw out, it is not necessary.

 

2. In order to use Finally to ensure the release of resources. Such as:

SqlConnection connection = null;

    try

    {

          connection = new SqlConnection(ConnectionString);

          connection.Open();

         …

    }

   catch (Exception ex)

    {

         throw ex;

    }

    finally

    {

         if (connection != null && connection.State != ConnectionState.Closed)

         {

              connection.Close();

         }

}

Catch live this situation Exception thrown out directly, without processing. Note that this use Try ... Catch is not the only way, you can also use the using statement to ensure the release of resources.

 

3. In order to ensure a unified export function. For example, the outermost layer of a continuous function calls a series of internal sub-functions and sub-functions when one of these errors, jump to the last exit function, this situation directly Exception Catch live to eat, because there has been done in error Try deal with. Such as:

public Result OutMostFunction()

    {

        Result result = Result.Success;

 

        try

        {

            try

            {

                SubFunction1();

            }

            catch (Exception ex)

            {               

                result = Result.SubFunction_1_Error;              

                throw ex;

            }

 

            try

            {

                SubFunction2();

            }

            catch (Exception ex)

            {

                result = Result.SubFunction_2_Error;

                throw ex;

            }

 

            try

            {

                SubFunction3();

            }

            catch (Exception ex)

            {

                result = Result.SubFunction_3_Error;

                throw ex;

            }

        }

        catch (Exception ex)

        {           

        }

 

        return result;

    }

 

4. In order to distinguish a program error and logic errors, requires a custom type Exception. For example, the outermost layer of a password authentication function call a subroutine, we need to distinguish because of wrong password (logical error), or in the process of password verification program appeared unexpected errors (bugs). Such as:

public class GoOutException : Exception {}

public Result OutMostFunction()

    {

        Result result = Result.Success;

 

        try

        {

            try

            {

                if (!VerifyPassword(password))

                {

                    result = Result.Invalid_Password;

                    throw new GoOutException();

                }

            }

            catch (Exception ex)

            {

                if (!(ex is GoOutException))

                {                   

                    result = Result.General_Error;                   

                }

                throw ex;

            }           

        }

        catch (Exception ex)

        {           

        }

 

         return result;

    }

 

 

 

 

 

 

 

 

 

    1. When to use try catch statement module, is not no clear answer?  
    2.   
    3. Answer from users: try catch an exception handling mechanism provided by the programming language itself, most of the code you write is to call the bottom of the api, api and these authors in the development of api, api clear in the use of process What there will be abnormal happens, he should inform the caller api, as to how to deal with this abnormal situation, it is handed over to the caller's api.  
    4.   
    5. You're writing code, you have to call api, api So you say the caller, you should deal with abnormal situations api itself exist, then how do you deal with these abnormal conditions, you mentioned that's try the catch role, and it is more do's. As there api which abnormal happens, we need to check the api help files; how to deal with these abnormal conditions, which in turn depends on the issue logic, and a relationship with the actual demand.  
    6. block try {A} catch {Exception e} {B} block. . . . .  
    7.   
    8. A block are more likely to go wrong, B is A, if the process has an error, performed. Like, on a line, if there was a place to have a product blocked illogical, if no one treatment, the entire pipeline would not be able action, and in order to ensure the operation of the entire pipeline will have someone to deal with this product . A statement is to try statement block of capture is likely to go wrong, which is equivalent to check on the assembly line of people, catch statement is processed.  
    9.   
    10. When the need to use try-catch it, that is, try not to use this structure under what circumstances, withdraw from the code error can not continue execution. Some error codes should withdraw, still some mistakes can be remedied, you should not quit. For this error should not withdraw from the need to use this structure, the remedy in the catch. For example, write a log file, if the log file is locked or occupied, so the writing will be wrong exit, but we do not want to see such a situation, we can then write a name change.  
    11.   
    12. After calling some function or functions not go wrong exit, but returns an error code, this time do not need to use the try-catch structure. Direct different error codes are classified according to processing on the line.  
    13. So instead of trycatch usage problem, or see the application scenario, if you do need to prevent abnormal exit, requiring multiple remedies, then more is not an exaggeration.  
    14. There is also a case to note, try-catch can not solve all the wrong exit, for example in the segment fault php, which is known as a segmentation fault, even if it is a try-catch still will withdraw, this time need to use gdb for debugging solved.  
    15.   
    16. After the try catch is not necessarily abnormal to output information? Or is there a better way to handle the log message?                                                                                    
    17. If each section of the program will try after the catch output log, the log information will lead to bloated, useful information can not be read from the log, making it more difficult to solve the problem. That there is no uniform treatment kit log it! Planned logs, exception information will be more clarity, at the same time to read the log can not segment the optimizer to reduce the occurrence of an abnormal situation, too why not!  
    18.   
    19. LOG4J learning  
    20. Definitions: Log4j is an open source Apache project, through the use of Log4j, we can control the destination log information delivery is the console, files, GUI components, or even socket servers, the event recorder NT, UNIX Syslog Daemon and the like; we can also control the output format of each log; each defined by a level of log information, we were able to more carefully control the log generation process. The most interesting is that these can be flexibly configured via a configuration file, without modifying the application code.  
    21. Logging program development environment is embedded in the program to output some useful information to developers composed statement. For example, the statement trace (trace), and a common structure dump or printf System.out.println debug statements. log4j classification method provides logging statements embedded in the program. The log information having a variety of output formats and a plurality of output levels.  
    22. Use a dedicated logging package, you can reduce maintenance cost tens of thousands of System.out.println statements, because logging can be controlled at runtime through configuration script. log4j maintenance program code embedded in the logging statement. By regulating logging process, some people think we should encourage more use of logging and achieve a higher degree of efficiency.  
    23.   
    24. Use log4j probably involve three main concepts:  
    25. Public class Logger Logger handles most operations logging.  
    26. Public interface Appender Appender responsible for controlling the output of the logging operation.  
    27. Public abstract class Layout Layout Appender responsible for formatting the output.

Guess you like

Origin www.cnblogs.com/BearLee/p/11010239.html