PHP Exception exception Handling and Exit/die

Source: Internet
Author: User
Tags try catch
It has been difficult to understand exception handling, such as the bottom of my program using the MySQL database connection, and my upper layer all the programs are built on this basis (regardless of the cache, etc.), such as a page to take out the current URL of the ID specified in the post content, when invoking the underlying database connection, the result Mysql_ Connect is unable to connect, the application built on this basis is no longer necessary to execute, my mysql_connect should not be directly exit/die terminate the program? Even if you want a friendly error hint, I can customize a function such as Myerror ($code), in this function to beautify my output and decide in the inside to Exit/die AH.

If you use exception handling, do I have to add try/catch when I think all may be wrong? Then my program is not a bunch of try/catch ... What is the difference between this and my direct use of die/exit or the invocation of custom Myerror ()? If you say that Exception can be passed on, but I often should immediately deal with AH, such as the database is not connected, or I include the system configuration when the file does not exist, this time should not be processed immediately?

For example, I made a single entrance, Router, Controllers, Services/models, Modelbase, dbfactory ter add a try/catch on the outside, all of them throw? For example, my MySQL mysql_connect problem, my Controller inside the Get ID, the URL ID in the database does not exist, both of which I would like to Try/catch/throw, and then Router outside the CA Tch in the middle of the process?

It is very confusing, seeking answers, manuals are taught how to use, did not teach the application scenario, and why use? (That's why I really don't see why), ask for advice! Can point out the specific application scenario the best, thank you ~

2015-06-19

Thank you very much for the detailed answer, thank you! There are still some questions to bother you, write in the comments are not very good, I took to write here.

For example, the configuration file is missing this problem, the method of processing:

1, the most primitive direct require, so that the configuration file does not exist directly error (Error open), this is obviously inappropriate, unfriendly and will expose the physical path.

2, I have been aware of the require may have problems, so decided to require before the is_file/file_exists to determine whether the file exists, then:

$file = '/a/b/c.php';is_file($file) or die('config file not found');require($file);

Or

$file = '/a/b/c.php';try{    is_file($file) or throw new Exception('config file not found');}catch(Exception $e){    //todo}require($file);

The first code may be a little bit simple, not many of the die can be replaced by custom error prompt function, you can also output friendly error message.

What is the benefit of the second code? Am I still throwing this $e in the//todo, or simply don't try/catch here? Suppose I was a single entry, and finally the entire system was Exception to the top layer of processing?

1, according to the concept of layered processing, now assume that the config code is "config layer", first of all, it is certain that my "dispatcher layer", "Controller Layer", "DB Layer", "model layer" all depend on it, Do I want these layers to deal with this anomaly on their own? Or do these layers throw themselves out again? Or all of these layers (I don't care, who's the last one)? This "config layer" is more than the other layer of service, that "config layer" should not be disposed of when the configuration file is lost? Does this not conform to the exception as far as possible non-proliferation?

2, by the "config layer" to deal with their own, that//todo treatment should not also exit/die it? Otherwise, it's going to be require again?

3, if it exit/die out of its own, this time the exception of the advantage is not just more than my custom myerror more than the trace information?

Reply content:

It has been difficult to understand exception handling, such as the bottom of my program using the MySQL database connection, and my upper layer all the programs are built on this basis (regardless of the cache, etc.), such as a page to take out the current URL of the ID specified in the post content, when invoking the underlying database connection, the result Mysql_ Connect is unable to connect, the application built on this basis is no longer necessary to execute, my mysql_connect should not be directly exit/die terminate the program? Even if you want a friendly error hint, I can customize a function such as Myerror ($code), in this function to beautify my output and decide in the inside to Exit/die AH.

If you use exception handling, do I have to add try/catch when I think all may be wrong? Then my program is not a bunch of try/catch ... What is the difference between this and my direct use of die/exit or the invocation of custom Myerror ()? If you say that Exception can be passed on, but I often should immediately deal with AH, such as the database is not connected, or I include the system configuration when the file does not exist, this time should not be processed immediately?

For example, I made a single entrance, Router, Controllers, Services/models, Modelbase, dbfactory ter add a try/catch on the outside, all of them throw? For example, my MySQL mysql_connect problem, my Controller inside the Get ID, the URL ID in the database does not exist, both of which I would like to Try/catch/throw, and then Router outside the CA Tch in the middle of the process?

It is very confusing, seeking answers, manuals are taught how to use, did not teach the application scenario, and why use? (That's why I really don't see why), ask for advice! Can point out the specific application scenario the best, thank you ~

2015-06-19

Thank you very much for the detailed answer, thank you! There are still some questions to bother you, write in the comments are not very good, I took to write here.

For example, the configuration file is missing this problem, the method of processing:

1, the most primitive direct require, so that the configuration file does not exist directly error (Error open), this is obviously inappropriate, unfriendly and will expose the physical path.

2, I have been aware of the require may have problems, so decided to require before the is_file/file_exists to determine whether the file exists, then:

$file = '/a/b/c.php';is_file($file) or die('config file not found');require($file);

Or

$file = '/a/b/c.php';try{    is_file($file) or throw new Exception('config file not found');}catch(Exception $e){    //todo}require($file);

The first code may be a little bit simple, not many of the die can be replaced by custom error prompt function, you can also output friendly error message.

What is the benefit of the second code? Am I still throwing this $e in the//todo, or simply don't try/catch here? Suppose I was a single entry, and finally the entire system was Exception to the top layer of processing?

1, according to the concept of layered processing, now assume that the config code is "config layer", first of all, it is certain that my "dispatcher layer", "Controller Layer", "DB Layer", "model layer" all depend on it, Do I want these layers to deal with this anomaly on their own? Or do these layers throw themselves out again? Or all of these layers (I don't care, who's the last one)? This "config layer" is more than the other layer of service, that "config layer" should not be disposed of when the configuration file is lost? Does this not conform to the exception as far as possible non-proliferation?

2, by the "config layer" to deal with their own, that//todo treatment should not also exit/die it? Otherwise, it's going to be require again?

3, if it exit/die out of its own, this time the exception of the advantage is not just more than my custom myerror more than the trace information?

Based on your problem, you need to have a certain abstraction, to have the concept of encapsulation, in fact, I prefer to call layering, that is, we want to establish a similar concept of the following:

上层角色 Upper Role------------------层分界线------------当前层角色 Current Role------------------层分界线------------下层角色 Lower Role

Based on the above concepts, both Exit/die and exception can be divided into 2 situations:

 a. Upper Role作为接受方,Current Role作为行为方 b. Current Role作为接受方,Lower Role作为行为方

For a, who do you want to consider the behavior of the recipient upper role? If the upper role is the top role, which is generally based on our application, the top role refers to the person using the browser, then you should use the Exit/die, which is the top role to handle, that is, all except the top role upper Role does not have the right to interfere, and when upper role is non-top role, then it should be used exception so that all upper role except top role is entitled to do some extra processing.

Based on the mysql_connect connection for a, (according to my design) when using mysql_connect, the current role refers to DB processing to connect MySQL-related logic, and upper Role is the unknown logic that calls the db (think of why I use the "unknown" concept here), current role only knows that the Mysql_connect connection fails, and does not know if upper role has other DB or additional options, then current Role in order for upper role to have a certain choice, here (i) choose to use exception, let upper role decision is given to top role processing or the upper upper role processing.

In the case of B, the current role is to determine if lower role is expected to have some non-current role expectations (i.e.: Exception), the following options

是否有非Current Role期望的情况如果没有,Current Role不需要try/catch,如果有,Current Role需要处理么?    Current Role需要处理,try/catch       Current Role可以处理?           可以处理,处理           Upper Role需要处理Current Role的非期望,throw              Current Role不需要处理,无视         

Based on the mysql_connect connection for B, current role refers to the logic required to use the DB, while the lower role is the DB processing connection MySQL related logic, when used in current role, the current Role expects MySQL to be able to connect normally, but the additional situation will also occur, then the current role should consider its own situation to choose, for example, current role is a select operation, then the current role can be returned to NULL, Then for MSYQL connection failure or the data table is really empty, the same nature, the current role can discard the non-expected (capture non-processing) return to NULL, and for an update, can choose to handle or not processing can, and for a can choose N mysql The logic of the connection, it must be handled, etc.

In short, wordy a bunch, that is, you want to use the good anomaly, then you have to have the concept of the upper and lower layers, and in the upper and lower layers of logic processing, to distinguish between the current role can terminate the program execution (exit) or to upper role processing (throw Excepton)

Finally, throw is current role feedback to upper role,try/catch is current role processing lower role feedback, I hope you can better use exception

Landlord should not understand the good abnormal execution mechanism , read the official PHP Manual on the description of the anomaly here.

Let's take a look at the Exception implementation process first without saying how the exception should be used.

try {    throw new Exception('This is first exception.');    echo 'AAA';} catch (Exception $e) {    echo 'BBB';}//这里会输出echo 'CCC';throw new Exception('This is second exception.');

What do you think is the result of the above output? Here's the answer.

BBBCCCFatal error: Uncaught exception 'Exception' with message 'This is second exception.' ...

From the above implementation results, we can see some features of exception:

    1. The try and catch must be paired, and try{} contains code that might throw an exception.
    2. once the code in try {} has an exception, the code after the exception stops executing. (This is specifically the code inside try{})
    3. after catching and processing the exception with catch () {}, the code after try{} and catch () {} echo 'CCC' will continue to execute .
    4. If the exception is not captured, a fatal error Fatal error is thrown.

In combination with the above characteristics, then the problem of sticking to the main question, it is easier to solve.

Question 1: Do you want a try catch for every place that has an exception?

My answer: This is too much trouble, and generally not necessary, you can use a try catch inclusion in all the places that might throw an exception . After the catch to the exception, who to deal with, how to handle all can. This also satisfies the single entrance, single export development concept .

Question 2: Are there errors, either thrown Exception or used die()/exit() ?

My answer: exception You can casually throw, but in the end you have to have a place to deal with . After processing (such as logging and so on), you will end up telling the front-end users that the process is output. In the event of an error, I recommend using an exception Exception because it conforms to the single export development concept so that you can monitor all page outputs. If you use it everywhere die()/exit() to output it directly, you can't control the output .

Furthermore, Exception it actually contains richer information, such as line number, error code, error stack information trace, and so on. So isn't it better?

Question 3: What is the application scenario problem?

My answer: Exceptions can be used in any situation, the key you want to Exception play a role. For example, when you write the API service program, any errors (including program exceptions, business logic errors, field type errors, etc.), all throw exceptions, all from a place to handle . In fact, I feel this kind of development experience is very good, because the first time I write, I am not used Exception , embarrassed ~. But here's a question:API It has no interface, it is only responsible for returning some data, and the return data format requirements are generally uniform specifications .

If you are writing a front-end program, I would like to write one side, can you use Exception : any program error thrown exception, any business validation error when using such as Return/echo/die return. because the exception can be expressed naturally is limited, if some errors (general business error) return is very complex, and the front-end application of non-API degrees of freedom is relatively large, with the exception may be inconvenient.

Above is their own humble opinion bar, there is no place, hope to point out, common progress! Get off work, leave ...

If you want to catch a global error, or an exception, see
http://cn2.php.net/manual/zh/function.set-error-handler.php
http://cn2.php.net/manual/zh/function.set-exception-handler.php

Allows you to catch an error or exception with a callable object

PHP Call exit script execution does not cause the PHP service to exit, this is fundamentally different from other languages, so other languages have to use Try/catch to catch exceptions or to determine the return value to further processing, PHP is not necessary.

Read this post: http://bbs.phpchina.com/thread-212378-1-1.html, my problem may not understand the exception, like the database is not connected or the configuration file is missing this may halt more security directly although a bit rough.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.