Exceptions in the 05-python

Source: Internet
Author: User

All of Python's exceptions inherit from the base class: Exception

Handled in a similar way to Java:

Path = Raw_input ('Input the path') Array= Path.split ('/')Try: module= __import__ ('model.'+ array[0]) Model= GetAttr (module, array[0]) func= GetAttr (model, array[1] func () except (Importerror, Attributeerror, Nameerror), E:print (e)finally: Print ('finally to do')

Multiple exception snaps, either using a continuous exept or using parentheses for snapping

Import SYSTry: F= Open ('MyFile.txt') s=f.readline () I=int(S.strip ()) except OSError asErr:print ("OS Error: {0}". Format (ERR)) except Valueerror:print ("Could not convert data to an integer.") Except:print ("Unexpected error:", Sys.exc_info () [0]) Raise
else:
Print (' Else method ')

Python's exception has an ELSE clause that executes without any exception.

Custom Exceptions:

Like other languages, Python can also make custom exceptions and throw them;

class myexception (Exception):    def __init__ (self, name):        = name    # Override string method     *args, * * Kwargs):        return self.name

The way to throw in other places:

Try :    print ('start ... ' )    raise MyException ('raise exception' as err:    print (ERR) finally :    print ('finally')

Use the Raise keyword to throw

Exceptions in the 05-python

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.