Talking about python throws exceptions, custom exceptions, passing exceptions, and python throws

Source: Internet
Author: User

Talking about python throws exceptions, custom exceptions, passing exceptions, and python throws

1. Throw an exception

Python uses an exception object to indicate exceptions. An exception is thrown when an error occurs. If the exception object is not processed or captured, the program terminates the execution with the so-called trace (Traceback, an error message.

Raise statement

The raise keyword in Python is basically the same as the throw keyword in C # and Java, as shown below:

Import tracebackdef throw_error (): raise Exception ("throwing an Exception") # The Exception is thrown, and the print function cannot execute print ("fliggy") throw_error ()

# Running result:

'''Traceback (most recent call last): File "C: \ Users \ Administrator \ Desktop \ mongoray. py ", line 7, in <module> throw_error () File" C: \ Users \ Administrator \ Desktop \ empty Ray. py ", line 4, in throw_error raise Exception (" throwing an Exception ") # The Exception is thrown, and the print function cannot execute Exception: throwing an Exception '''

The raise keyword is followed by a general Exception type (Exception). Generally, the more detailed the Exception is, the better.

Ii. Transfer exception:

If an exception is caught, but you want to re-raise 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)

Iii. custom exception types:

You can also customize your own special types of exceptions in Python. You only need to inherit from the Exception class (either 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.