Which of the following is better for Python to handle exceptions and errors?

Source: Internet
Author: User
BeginningPythonFromNovicetoProfessional, 2 ndEdition, CHAPTER8, EXCEPTIONS, Page173: description in the body: Second (more "Pythonic") th Beginning Python From Novice to Professional, 2nd Edition, CHAPTER 8, EXCEPTIONS, Page 173:


The text is described as follows:


The point is that using try/Login T statements is in your cases much more natural (more "Pythonic") than if/else, and you shoshould get into the habit of using them where you can.1


Note:


1. the preference for try/retry t in Python is often explained through Rear Admiral Grace Hopper's words of wisdom, "It's easier to ask forgiveness than permission. "This strategy of simply trying to do something and dealing with any errors, rather than doing a lot of checking up front, is called the Leap Before You Look idiom.


--------------------------------


Python basic tutorial (version 2nd), Chapter 8th, exception, page 136th:


In many cases, it is more natural to use the try/else t statement than to use the if/else Statement (more "Python"). You should try to use the if/else statement as much as possible. ①


① Try/try t statement performance in Python can be explained in the phrase "request forgiveness is easy to request permission ." Handle possible errors when you do one thing, instead of conducting a lot of checks before you start, this strategy can be summarized as the idiom "Leap Before You Look )".


---------------------------------


My understanding of the previous English is to allow readers to use more try/else t, while the translation of Chinese is to use more if/else. Is it wrong for me to understand or translate?

Reply: Dustin Getz's blog

It is best to use monad. There is no best way.
If there is a high probability of hit, use try... else t.... Otherwise, use if... else... to minimize the index check and exceptions. The Python skills in this article are indeed encouraging the use of try. In general, your code should be a try block. The following is a string of try t to handle various exceptions, instead of setting an if statement.

For more information, see monad ...... I also agree to use monad, but the python lambda with his indent is really ugly. You understand it correctly. Translation is incorrect.

However, I personally think it is not correct for the English version of this book.

The existence of the method must have its Application Scenario. If you don't have a hammer in your hand, you can see that everything is a nail.

To put it simply, as a user, you should determine the method used to handle errors according to the habits of the database in use. if the database uses throw, try. if the database uses return, if.
However, you can choose different models based on the development time and the importance of the modules.
For example, if the development time is short and the script is temporary, try-release T. if the code is more critical and requires stability, if-else is required if error c requires a detailed error prompt.

Therefore, the correct habit is not to get used to a specific problem, but to select a solution based on the specific scenario.
The subject has bought pirated copies ~ Last month, I was quite impressed. I remember that the book clearly shows try/try t. I will go back to school tomorrow. I have put all my books in my bags. Before I go to bed, I find this problem and I will read it out. Well, I remember it wrong. I should have bought pirated copies. Second (second) Second
Let's talk about some of my personal reading experiences. When I read such technical books, I will always encounter some sentences that I don't understand for the time being. Don't let them die, the focus is on what the purpose of this sentence is (for example, to describe a programming concept or technique). This is usually the title of the section in which the sentence is located. So let's put the sentence aside first, next, let's look at it. Maybe we can figure out the purpose.
For the same thing, different people may have different Descriptive methods because of their different experiences and environments. The authors write books to disseminate and share certain technologies, and most of them are not the creators of technologies, the purpose of reading a book is to master this technology and use it for production practice, without having to explain the statements of this technology to the author. For example, when you understand a technology, when you explain it like someone else, it will surely have your own personal style. The broken night bird will have to get up at 6 o'clock tomorrow morning to catch the shuttle bus to go back to school by train in the city, and then look for several examples from the book ~
PS: the mobile phone number is used. The picture is being uploaded at the time of release. Please wait... Drunk
========================================================== ===
Updated on April January 9: I uploaded the cover and example of the book on a pc, and briefly divided it into the next section.
For example, when I saw the eight queens Problem in chapter 9 (I didn't understand what the eight queens meant at the time, I will first search for the concept of Queen eight, but it is not necessary, because the goal of the author is to let us know how to use generators to solve complex recursive problems, instead of understanding the concept of the queen of eight, we naturally understand the concept of the queen of eight in the subsequent code reading and understanding, so that there is no need to distract the search and lead to unnecessary time waste. Try again t I think try again t is enough, which can be used to quickly locate errors and avoid paralysis caused by unknown errors. Two cases:
1. for unknown exceptions, try... try t.
2. You can use if... else... to handle the exception.
----------
Python exception handling is not as powerful as java. I prefer scala's error handling mechanism. No if else, no try catch, and no NullException.

Scala provides the Option mechanism to solve the problem of checking null constantly in the code. Goodbye NullException

This example encapsulates the getProperty method and returns an Option. In this way, the null check is no longer aimlessly performed. You only need the Option type value.

Pattern match is a common practice. You can also use getOrElse to provide the default value when it is None.

What is awesome is that Option can also be viewed as a List with a maximum length of 1. The powerful functions of List can be used.


Def getProperty (name: String): Option [String] = {
Val value = System. getProperty (name)
If (value! = Null) Some (value) else None
}

Val osName = getProperty ("OS. name ")

OsName match {
Case Some (value) => println (value)
Case _ => println ("none ")
}

Println (osName. getOrElse ("none "))

OsName. foreach (print _)
Output result:
Linux
Linux
Linux
Reference address: Scala Tour

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.