Python3 and C # Object-oriented ~ Exception correlation

Source: Internet
Author: User
Tags ming

Weekend multi-code text, yesterday evening an article, today another article:

Online Programming: Https://mybinder.org/v2/gh/lotapp/BaseCode/master

Online preview: HTTP://GITHUB.LESSCHINA.COM/PYTHON/BASE/OOP/3. Exception-related. html

Code pants: https://github.com/lotapp/BaseCode/tree/master/python/2.OOP/4.Exception

1. Abnormal ¶1.1 try...except¶

Another time to open a new class, Xiao Ming's classmates this time to preview the knowledge, riding the teacher has not come on the blackboard to write down this paragraph code:

In [1]:
def Main ():    Try :        1 / 0  # Zerodivisionerror:division by Zero    except Zerodivisionerror  as ex :        Print (ex) if __name__ == ' __main__ ' :    Main ()
Division by zero
1.2 try...except...else...finally¶

Pen classmate just came in and saw, himself way: " try...except catch abnormal who won't?" It's going to be so damn nice. Show, cut ~ I give you the format to complete "

So when Xiao Ming went to the bathroom, erase Xiao Ming's code, wrote a tall on the code:

In [2]:
# Exception capture full formatdef Test(Input_str):    Try:        Eval(Input_str)    except Zerodivisionerror  as ex:        Print("except:", ex)    Else:        Print("Else: Reward 100 bucks without exception")    finally:        Print("Finally: Xiao Ming is a fool ~")def Main():    Test("1/0")    Print("-" * Ten)    Test("Print (' Xiao Ming Xiao Ming you tune in the Hole ~ ')")if __name__ == ' __main__ ':    Main()
Except:division by zerofinally: Xiao Ming is a fool ~----------Xiao Ming you tune in the pit ~else: no exception on the Reward 100 block ~finally: Xiao Ming is a fool ~

At this time, Xiao Ming and the teacher came in, the students vaguely heard the voice of Xiao Ming's boast: "Teacher, I am well, early preview and also wrote a demo on the blackboard it ~"

The teacher smiled at the door and looked at the blackboard, and the classmates laughed as a piece. Xiao Ming thought, hey ~ i wrote the wrong? Fixed eye A look at the blackboard, angrily back to the seat

elseCan not write, but we will basically write, after all, we can know that there is no error, but not to block the error

1.3 + Exception Handling ¶

The teacher is very gratified, think this class is really interesting, everyone learning unprecedented enthusiasm, in order to take care of Xiao Ming, the teacher asked: "Who knows how to deal with multiple exceptions ?" ”

Xiaoming quickly raised his hand and wiped out the contents of the blackboard and wrote the following code:

In [3]:
# Multiple exception capturesdef Main():    Try:        Print(Xiaopan)  # nameerror:name ' Xiaopan ' is not defined        1 / 0  # Zerodivisionerror:division by Zero    except Nameerror  as ex:        Print(ex)    except Zerodivisionerror  as ex:        Print(ex)if __name__ == ' __main__ ':    Main()
Name ' Xiaopan ' is not defined

The teacher asked Xiao Ming a sound, how many output?

Xiao Ming proudly said: "Two, I wrote two exception handling, of course, all executed."

The students laughed again, Xiao Pan joked about the sentence: "A look at the last year C # did not learn, this is not the same, encountered an exception the following code is also executed ? Think about it in your head.

When we think that some code may be wrong, it can be used try to run the code, if the execution error, the subsequent code will not continue to execute, but directly jump to the except statement block, except after execution, if there is a finally block of statements, then execute the FINALLY statement block

Xiao Ming is embarrassed again ...

1.4 Multiple Exception Shorthand ¶

The teacher once again help Xiao Ming round a field: "Already very not simple, is the last little proud of the time of the slip of the tongue, that Xiao Ming classmate you know how unusual python inside a convenient way to do?" ”

Xiao Ming hurriedly picked up the chalk brush to finish writing, then said: "Ofcourse"

In [4]:
# Shorthand for multiple exception captures (note Oh, it's tuples OH)def Main():    Try:        Print(Xiaopan)  # nameerror:name ' Xiaopan ' is not defined        1 / 0  # Zerodivisionerror:division by Zero    except (Nameerror, Zerodivisionerror)  as ex:        Print(ex)if __name__ == ' __main__ ':    Main()
Name ' Xiaopan ' is not defined

The teacher hurriedly praised Xiao Ming, thought, hey yo finally put this tough guy back to his seat.

Xiao Ming left before he forgot to say: "Shorthand note format Oh, is the tuple is not comma-separated"

Teacher This class is very relaxed, everyone has previewed and the content is relatively simple.

Then asked the question: "Pen classmate, do you know what the base class is?" What do you do if you want to catch all the exceptions? ”

Pen stood up and said, "Yes BaseException ."

The teacher expands: "All the error types inherit from BaseException , so except when you use it, it's important to note that it not only captures the type of error, but also captures its subclasses together."

So usually when catching an exception , the class exception is placed in front, the parent class is placed behind

Look at the following code:

In [5]:
def Main():    Try:        1 / 0  # Zerodivisionerror:division by Zero    except baseexception  as ex:        Print("Base:", ex)    except Zerodivisionerror  as ex:        Print(ex)if __name__ == ' __main__ ':    Main()
Base:division by Zero

If you put the parent class first, then will ZeroDivisionError never be executed, in fact, if you installed a code specification hint plug-in will prompt you

You can refer to the Vscode I wrote earlier to set up the Python3 Debug Environment Extension Section

A shorthand for generic exception captures (the official deprecated shorthand):

In [6]:
# Direct except on the line def Main ():    Try :        1 / 0        dnt += 1    except :        Print ("masking error") if __name__ == ' __main__ ' :    Main ()
Masking errors

The teacher continues to talk about, we look at a scene, now a lot of online editor, you write in their edit box code is also an exception to throw, this is how to deal with it?

Microsoft has an open source code editor that is popular (part of Vscode): Monaco-editor

Hint, if you really want to do online editor, remember to think about fork炸弹 this is actually very old things, programmers should basically contact

1.5 Throwing Exceptions ¶

We continue, like C # is thorw thrown with exceptions, that python how? 捕获异常后再抛出 What is 自定义异常 it?

Keep looking down:

In [7]:
# After catching an exception and then throwing it, eg: User code for online operation def Main ():    Try :        1 / 0  # Zerodivisionerror:division by Zero    except Zerodivisionerror  as ex :        Print (ex)  # Write a log, go back to        the problem Raise if __name__ == ' __main__ ' :    Main ()
Division by zero
---------------------------------------------------------------------------ZerodivisionerrorTraceback (most recent)<ipython-input-7-15f01346e2d8>Inch<module>()9 Ten if__name__== ' __main__ ':--->Main()<ipython-input-7-15f01346e2d8>InchMain()2 defMain():3     Try:----> 41 / 0  # Zerodivisionerror:division by Zero5     exceptZerodivisionerror asEx:6Print(Ex)  # Write a log, go back to the problemZerodivisionerror: Division by zero
In [8]:
# Throw a custom exceptionclass dntexception(baseexception):    Passdef Get_age(Num):    if Num <= 0:        Raise dntexception("num must>0")    Else:        Print(Num)def Main():    Get_age(-1)    Get_age( A)  # The program is broken, this sentence won't be executed.if __name__ == ' __main__ ':    Main()
---------------------------------------------------------------------------dntexceptionTraceback (most recent)<ipython-input-8-7c9dec6ec225>Inch<module>() -  - if__name__== ' __main__ ':--->Main()<ipython-input-8-7c9dec6ec225>InchMain() A  - defMain():--->Get_age(-1) theGet_age( A)  # The program is broken, this sentence won't be executed. - <ipython-input-8-7c9dec6ec225>InchGet_age(num)6 defGet_age(Num):7     ifNum<= 0:----> 8RaiseDntexception("num must>0")9     Else:TenPrint(Num)dntexception: Num must>0

Exception this piece is basically finished ( logging after the module will say) What can be said to add ^_^

Python3 and C # Object-oriented ~ Exception correlation

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.