11B-43 NGUYỄN DUY TIẾN
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    ### Exception * If the codes go wrong, python **stop the program and create exception (raising an exception)** * What happens: * python expect coders take care of it * if not, forcibly terminate the program and error message will occur * if handled, the program continue * We can **observe exceptions, identify them and handle them** * exception name: > ValueError: math domain error > ZeroDivisionError: division by zero > IndexError: list index out of range ### Handle Exception * Use `try` as a keyword * Idea: * first, you have to try to do something; * next, you have to check whether everything went well. * Another way to handle wrong codes: check first and do it if it is safe. * But it is **bloated and illegible** * Example: ``` first_number = int(input("Enter the first number: ")) second_number = int(input("Enter the second number: ")) if second_number != 0: print(first_number / second_number) else: print("This operation cannot be done.") print("THE END.") ``` * **favorite Python approach** > try: : : except: : : * Note: * the try keyword begins a block of the code which may or may not be performing correctly * the except keyword starts a piece of code which will be executed if anything inside the try block goes wrong ![](https://hackmd.io/_uploads/r1ryvra03.png) ```python try: print("1") x = 1 / 0 print("2") except: print("Oh dear, something went wrong...") print("3") # Output: 1, Oh dear, something went wrong..., 3 # print 2 bị bỏ qua ``` * disadvantage: if 2 or more exceptions raised, we didn't know which is the reason from the input. Example: ```python try: x = int(input("Enter a number: ")) y = 1 / x except: print("Oh dear, something went wrong...") print("THE END.") #non-integer data entered by the user; # x=0 # It just outputs "Oh dear, something went wrong..." ``` * **2 ways to solve this issue:** * build two consecutive try-except blocks, one for each possible exception reason (easy, but will cause unfavorable code growth) * use a more advanced variant of the instruction. ```python try: : except exc1: : except exc2: : except: : ``` ![](https://hackmd.io/_uploads/SyaZiHaCn.png) * Example: ```python try: x = int(input("Enter a number: ")) y = 1 / x print(y) except ZeroDivisionError: print("You cannot divide by zero, sorry.") except ValueError: print("You must enter an integer value.") except: print("Oh dear, something went wrong...") print("THE END.") # if you enter a valid, non-zero integer value (e.g., 5) # output:0.2 THE END. # # if you enter 0 # output: You cannot divide by zero, sorry. THE END. # # if you enter any non-integer string # output: You must enter an integer value. THE END. # # if you press Ctrl-C while the program is waiting for the user's input (which causes an exception named KeyboardInterrupt) # output: Oh dear, something went wrong...THE END. ``` ![](https://hackmd.io/_uploads/S1-YTraC2.png) * Nếu ko có branch nào handle dc thì nó vẫn raise error: ``` try: x = int(input("Enter a number: ")) y = 1 / x print(y) except ValueError: print("You must enter an integer value.") print("THE END.") # output: ZeroDivisionError: division by zero ``` ### Cấu trúc của exception * Có 63 built-in exceptions, tạo ra tree-shaped hierarchy * Built-in exceptions có genral(include mấy exceptions khác) và chỉ 1 mình nó * **the closer to the root an exception is located, the more general (abstract) it is** * leaves là những exception cuối của nhánh (giống tree graph) ![](https://hackmd.io/_uploads/SkNbMIpRh.png) * example of a branch from ZeroDivsionError: ![](https://hackmd.io/_uploads/BJBQM8T0n.png) * Some example ```python try: y = 1 / 0 except ZeroDivisionError: print("Oooppsss...") print("THE END.") # if we change ZeroDivisionError to ArithmeticError or Exception or BaseException, # it still outputs "Oooppsss..." ``` ![](https://hackmd.io/_uploads/By5i7ITCh.png) ```python try: y = 1 / 0 except ZeroDivisionError: print("Zero Division!") except ArithmeticError: print("Arithmetic problem!") print("THE END.") # output: Zero division! THE END. try: y = 1 / 0 except ArithmeticError: print("Arithmetic problem!") except ZeroDivisionError: print("Zero Division!") print("THE END.") # output: Arithmetic problem! THE END. # The first is better because the message is more concrete. ``` ![](https://hackmd.io/_uploads/ByqTE8T0h.png) #### handle two or more exceptions ```python try: : except (exc1, exc2): : ``` * exception is raised inside a function, it can handled inside and outside ```python def bad_fun(n): try: return 1 / n except ArithmeticError: print("Arithmetic Problem!") return None bad_fun(0) print("THE END.") # output: Arithmetic problem! THE END. def bad_fun(n): return 1 / n try: bad_fun(0) except ArithmeticError: print("What happened? An exception was raised!") print("THE END.") # What happened? An exception was raised! THE END. ``` ![](https://hackmd.io/_uploads/SyBtwLa02.png) #### Raise ```python def bad_fun(n): raise ZeroDivisionError try: bad_fun(0) except ArithmeticError: print("What happened? An error?") print("THE END.") # output: What happened? An error? THE END. ``` * The Python statement raise ExceptionName can raise an exception on demand. The same statement, but lacking ExceptionName, can be used inside the except branch only, and raises the same exception which is currently being handled. #### Assert > assert expression * How does it work? * It evaluates the expression; * If it is True, it will go through, else, it will raise AssertionError ```python def divide(x, y): assert y != 0, "Cannot divide by zero" return x / y result = divide(10, 2) # No assertion error print(result) # Output: 5.0 result = divide(10, 0) # Assertion error is raised ``` * The Python statement assert expression evaluates the expression and raises the AssertError exception when the expression is equal to zero, an empty string, or None. You can use it to protect some critical parts of your code from devastating data. ```python def foo(x): assert x return 1/x try: print(foo(0)) except ZeroDivisionError: print("zero") except: print("some") # The ouput is some because we met the assertion error before ZeroDivisionError. ``` [Link for references (must read)](https://studyglance.in/python/raise-assert.php) #### Some exceptions ##### Built-in exceptions * **ArithmeticError** * Location: BaseException ← Exception ← ArithmeticError * Description: an abstract exception including all exceptions caused by arithmetic operations like zero division or an argument's invalid domain * **AssertionError** * Location: BaseException ← Exception ← AssertionError * Description: a concrete exception raised by the assert instruction when its argument evaluates to False, None, 0, or an empty string * **BaseException** * Location: BaseException * Description: the most general (abstract) of all Python exceptions - all other exceptions are included in this one; it can be said that the following two except branches are equivalent: except: and except BaseException:. * **IndexError** * Location: BaseException ← Exception ← LookupError ← IndexError * Description: a concrete exception raised when you try to access a non-existent sequence's element (e.g., a list's element) * **KeyboardInterrupt** * Location: BaseException ← KeyboardInterrupt * Description: a concrete exception raised when the user uses a keyboard shortcut designed to terminate a program's execution (Ctrl-C in most OSs); if handling this exception doesn't lead to program termination, the program continues its execution. * **LookupError** * Location: BaseException ← Exception ← LookupError * Description: an abstract exception including all exceptions caused by errors resulting from invalid references to different collections (lists, dictionaries, tuples, etc.) * **MemoryError** * Location: BaseException ← Exception ← MemoryError * Description: a concrete exception raised when an operation cannot be completed due to a lack of free memory. * **OverflowError** * Location: BaseException ← Exception ← ArithmeticError ← OverflowError * Description: a concrete exception raised when an operation produces a number too big to be successfully stored * **ImportError** * Location: BaseException ← Exception ← StandardError ← ImportError * Description: a concrete exception raised when an import operation fails * **KeyError** * Location: BaseException ← Exception ← LookupError ← KeyError * Description: a concrete exception raised when you try to access a collection's non-existent element (e.g., a dictionary's element) * **Exceptions are in fact objects**

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully