Python's handling strategy for exceptions and errors, with try...except, or if...else ..., which is better?

Source: Internet
Author: User
Beginning Python from Novice to Professional, 2nd Edition, CHAPTER 8, EXCEPTIONS, Page 173:


This description in the body:


The point was that using try/except statements are in many cases much more natural (more ' pythonic ') than If/else, and you s Hould get into the habit of using them where do you can.1


Comments:


1. The preference for try/except in Python is often explained through Rear Admiral Grace Hopper ' s Words of Wisdom, "It's E Asier to ask forgiveness than permission. " This strategy of simply trying to does something and dealing with any errors, rather than doing a lot of checking up front, is called the Leap before your look idiom.


————————————————————————————————


Basic Python Tutorial (2nd Edition), chapter 8th, exceptions, page 136th:


In many cases, using try/except statements is more natural (more "python") than using If/else, and you should develop the habit of using IF/ELSE statements whenever possible. ①


The performance of the ①try/except statement in Python can be explained by the witty remarks of Admiral Grace Hopper: "It's easy to ask for forgiveness." "When doing something to deal with a possible error, instead of having to do a lot of checking before starting things, this strategy can be summed up as an idiom" jump (leap before look) before you start.


—————————————————————————————————


My understanding of the previous English is to allow readers to use try/except, and the Chinese translation is to say that more use If/else, is I understand wrong, or translation errors?

Reply content:

Dustin Getz ' s blog

Use Monad best. There's no best way.
If the probability of a hit is relatively large, then use try...except ..., instead of if...else ..., the reason is to minimize index checks and generate exceptions. This article speaks of the Code of the agricultural version of Python is really encouraged with a try, roughly your code should be a try block, followed by a string of except processing various exceptions, rather than each statement outside the set of an If.

For high-end see monad ... I also agreed to use Monad, but the Python lambda was too ugly to fit into his indentation. You understand right, there are mistakes in translation.

However, the English version of the Book of If-else and Try-except understanding, the individual feel is not correct.

The existence of the way must have its application of the scene, do not have a hammer in the hand to see what are nails.

Simply put, as a user, you should use the library's habits to decide which way to handle the error, if the library uses throw then try if the library uses return.
Their modules, depending on the development time and the importance of the module, choose different models.
For example, the development time is short, the script is temporary try-except, if the code comparison key requirements are stable, such as error C requires detailed error hint if-else.

Therefore, the correct habit is not to get used to having a certain, but should be specific problem specific analysis according to specific scenarios to choose the solution of the problem.
The main buy pirated ~ last month to see, the impression is quite deep, I remember the book is clearly try/except. Tomorrow back to school, the books have been put in the bag, to sleep before brushing know, see this problem, turned out to see, well, I remember correctly, the main problem is to buy pirated. ╮(╯▽╰)╭
Again, some of my personal reading experience, see this technical book, will encounter some temporarily do not understand the sentence, then do not always die to hold them, the focus is to see what the purpose of this sentence (such as the elaboration of a programming concept or technique), which is usually the sentence in the paragraph of the small title, So first put that sentence aside, and then look down, perhaps to understand the purpose.
The same thing, different people because of their different experiences and the environment will have different description methods, the author wrote books to spread and share a technology, most authors are not technology creators, we read the purpose is to master this technology, can use this technology for production practice, Without the need to explain the technology to the author of the statement to the understanding of the least bit. For example, when you understand a technology, you will have your own personal style when explaining the technology to others. You'll have to get up at 6 o ' clock in the morning. Go back to school by train, go back to school and find some examples from the book ~
PS: With mobile phone code, publish the total appearance of the picture is crossing, please later ... Drunk.
===========================================
January 9 Update: Upload the book's cover and examples with a PC, and simply divide the next paragraph.
For example, when I saw the eight Queens question in chapter Nineth (I did not understand the meaning of the eight queens), I would have searched the concept of the eight queens before I had done so, but it was not necessary because the author's purpose in lifting the eight queens was to let us know how to solve complex recursion problems with generators. Instead of understanding the concept of the eight queens, and in the next code reading comprehension, we naturally understand the concept of the eight queen, so that we do not have to be distracted by the search and lead to unnecessary time wasted. Try except I think the try except enough to be able to quickly check the wrong, easy to locate, but also to avoid the paralysis caused by unknown errors. Two cases:
1. Unknown exception with Try...except.
2. The foreseeable can be used if. else.. Under processing.
----------
Python's exception handling is not as powerful as Java. I prefer Scala's error handling mechanism. There is no if else no try catch without nullexception.

Scala provides the option mechanism to solve the problem of constantly checking for null in code. Bye, nullexception.

This example wraps the GetProperty method so that it returns an option. This allows for no more aimless null checks. Just the value of the option type.

Using pattern match to check is a common practice. You can also use Getorelse to provide the default value when none is true.

The force is that option can also be seen as a powerful feature of the list,list with a maximum length of 1.


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.