On Python throwing exceptions, custom exceptions, passing exceptions

Source: Internet
Author: User
I. Throwing an exception

Python uses an Exception object (Exception object) to represent an exception, and an exception is thrown when an error is encountered. If the exception object is not handled or captured, the program terminates execution with the so-called backtracking (Traceback, an error message).

Raise statements

The Raise keyword in Python is used to throw an exception, basically the same as the throw keyword in C # and Java, as follows:

Import Tracebackdef throw_error ():  raise Exception ("throws an exception") #异常被抛出, the print function cannot execute  print ("Flying Pig")  Throw_ Error ()

#运行结果:

"' Traceback (most recent): File" C:\Users\Administrator\Desktop\systray.py ", line 7, in 
 
  
   
    throw_ Error () File "C:\Users\Administrator\Desktop\systray.py", line 4, in Throw_error  raise Exception ("Throw an exception") #异常被抛出, The print function cannot execute exception: throws an exception '
 
  

The Raise keyword is followed by a generic exception type (Exception), which generally throws an exception the more detailed the better

Two. Passing Exceptions:

Catching an exception, but trying to re-throw it (passing an exception), you can use the Raise statement without parameters:

Class Mufcalc (object):  m = False  def calc (self,exp):    try:      return eval (exp)    except Zerodivisionerror:      if self.m:        print ("cool")      else:        Raiseapp = Mufcalc () app.calc (2/0)

three. Custom Exception Types :

Python can also customize its own special type of exception, only to inherit from the exception class (directly or indirectly):

Class Myerror (Exception):  Pass
  • 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.