Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python
Python
  1. RuntimeErrors ใน Python คืออะไร

    Syntax Error: Python ไม่เข้าใจ code (compile time) Runtime Error: Python เข้าใจ code แต่ error ตอนรัน (run-time) ตัวอย่าง a = input(Enter a number:) b = input(Enter a number:) c = a*b print(c) ผลลัพธ์ Enter a number: 7 Enter a number: 8 56 Code syntactically correct แต่อาจ error ตอนรัน (เช่น input ไ

  2. วิธี Pass Variable ให้ Exception ใน Python

    สร้าง custom exception class มี __init__ รับ variable ตัวอย่าง class ExampleException(Exception): def __init__(self, foo): self.foo = foo try: raise ExampleException(Bar!) except ExampleException as e: print(e.foo) ผลลัพธ์ Bar!

  3. วิธี Implement User-defined Exception ใน Python

    สร้าง class สืบทอดจาก Exception ตัวอย่างครบ: Guess the alphabet game # Python user-defined exceptions class CustomException(Exception): Base class for other exceptions pass class PrecedingLetterError(CustomException): Raised when entered alphabet is smaller than actual pass class S

  4. วิธี Raise Exception ใน Python

    ใช้ keyword raise Syntax raise [Exception [, args [, traceback]]] ตัวอย่าง: Raise ValueError ถ้า input ไม่ใช่ positive integer # raise_error.py try: i = int(input(Enter a positive integer value: )) if i <= 0: raise ValueError(This is not a positive number!!) except ValueError as e:

  5. วิธี Pass Argument ให้ Exception ใน Python

    Exception สามารถรับ argument ได้ (เพิ่ม info) จับได้ด้วย variable ใน except clause ตัวอย่าง try: b = float(56 + 78/0) except Exception as Argument: print(This is the Argument\n, Argument) ผลลัพธ์ This is the Argument integer division or modulo by zero Single exception: variable หลังชื่อ exce

  6. วิธีใช้ Try-Finally Clause Handle Exception ใน Python

    finally clause รันเสมอ ไม่ว่าจะมี exception หรือไม่ (cleanup/termination) กฎ: try ต้องมี either except หรือ finally (ไม่รวมกันได้ใน Python 2, Python 3 รวมได้) ตัวอย่าง try: foo = open(test.txt, w) foo.write(Its a test file to verify try-finally in exception handling!!) print(try block ex

  7. วิธีใช้ Except Clause กับ Multiple Exceptions ใน Python

    ระบุ multiple exceptions ใน tuple เดียว ใช้ as สำหรับ variable Syntax except (Exception1, Exception2, ...) as e: ตัวอย่าง import sys try: d = 8 d = d + 5 # TypeError except (TypeError, SyntaxError) as e: print(sys.exc_info()) ผลลัพธ์ (, TypeError(unsupported operand type(s) for +: int

  8. วิธี Ignore Exceptions ใน Python อย่างถูกต้อง

    1. Bare except + pass (จับ BaseException รวม KeyboardInterrupt, SystemExit) try: x, y = 7, 0 z = x/y except: pass 2. except Exception + pass (ไม่จับ KeyboardInterrupt, SystemExit) try: x, y = 7, 0 z = x/y except Exception: pass แนะนำ: ใช้ sys.exc_clear() ล้าง exception record

  9. วิธีใช้ Except Clause โดยไม่ระบุ Exception ใน Python

    except: โดยไม่ระบุ exception จะ catch ทุกอย่าง (bare except) ตัวอย่าง try: print(foo + qux + 7) except: print(There is error) ผลลัพธ์ There is error ไม่แนะนำ: ไม่รู้ว่าเป็น exception อะไร ไม่ช่วย debugging จับ BaseException รวมถึง KeyboardInterrupt, SystemExit ด้วย

  10. อธิบาย Try Except Else Statement ใน Python

    else clause หลัง except รันเมื่อ ไม่มี exception ใน try block ตัวอย่าง a = [11, 8, 9, 2] try: foo = a[3] except: print(index out of range) else: print(index well within range) ผลลัพธ์ index well within range else รันเมื่อ control flow ออกจาก try block ปกติ (ไม่ใช่ exception, return, con

  11. มี Standard Way ใช้ Exception Chains ใน Python 3 หรือไม่

    Python 3 รองรับ Exception Chaining ด้วย raise ... from ปัญหา Python 2: Exception A หายไปถ้า Exception B เกิดระหว่าง handling Python 3 Solution: try: s = {a:1, b:2}[c] except KeyError as e: raise ValueError(failed) from e ผลลัพธ์ Python 3 Traceback (most recent call last): File source_file.

  12. วิธี Manual Throw/Raise Exception ใน Python

    ใช้ raise กับ specific exception constructor ตัวอย่าง import sys try: f = float(Tutorialspoint) print(f) raise ValueError except Exception as err: print(sys.exc_info()) ผลลัพธ์ (, ValueError(could not convert string to float: Tutorialspoint,), ) Raise พร้อม arguments: try: raise

  13. Best Way เพื่อ Log Python Exception

    ใช้ logging.exception() ภายใน except block ตัวอย่าง import logging try: print(toy + 6) except Exception as e: logging.exception(This is an exception log) ผลลัพธ์ ERROR:root:This is an exception log Traceback (most recent call last): File ..., line 3, in print(toy + 6) TypeError: cann

  14. วิธี Declare Custom Exceptions ใน Modern Python

    Modern Python (3.x) ใช้ super() และเก็บ extra arguments ตัวอย่าง class ValidationError(Exception): def __init__(self, message, errors): super(ValidationError, self).__init__(message) self.errors = errors สามารถส่ง dictionary ของ error messages ไปใน parameter ที่สอง และเข้าถึงได้ภ

  15. ทำไม Python Exceptions ชื่อลงท้าย Error (ZeroDivisionError, NameError)

    เหตุผลที่ชื่อลงท้าย Error: สั้นกว่า Exception ประหยัดตัวอักษร ไม่สูญเสียความหมาย Historical reason: ใน Python แยก Errors (syntax errors) กับ Exceptions (runtime) แต่ naming convention คงอยู่ ไม่ใช่ทุก Exceptions ที่เป็น Errors: SystemExit, KeyboardInterrupt, StopIteration, GeneratorExit เป็น Except

  16. วิธี Capture และ Print Python Exception Message

    1. ใช้ attribute .message (Python 2) try: a = 7/0 print(float(a)) except BaseException as e: print(e.message) ผลลัพธ์ integer division or modulo by zero 2. ใช้ sys.exc_value (Python 2) import sys def catchEverything(): try: a = sequel b = 0.8 print(a + b)

  17. วิธี Handle Exception ที่โยนจาก Except Clause ใน Python

    ถ้า code ใน except clause เอง raise exception ใช้ nested try-except ตัวอย่าง import sys try: a = john # NameError except: try: 4/0 # ZeroDivisionError except: print(sys.exc_info()) ผลลัพธ์ (, ZeroDivisionError(integer division or modulo by zero,), ) Exception ตัวที่สอง

  18. วิธีอธิบายว่า Exception เป็น Object ใน Python

    ใน Python ทุกอย่างคือ Object รวมถึง Exceptions Exception object มี attributes และ methods เช่นเดียวกับ list, function, tuple Base class: Exception Attributes: e.args, e.message Current implementation: exceptions ประกอบด้วย 3 ส่วน (type, value, traceback) เข้าถึงได้ผ่าน sys.exc_info() ตัวอย่าง outp

  19. วิธีดึง Python Exception Text

    ใช้ sys.exc_info() คืน tuple (type, value, traceback) type: exception type value: error message traceback: stack snapshot ตัวอย่าง: ดึง type, filename, line number import sys, os try: raise NotImplementedError(No error) except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info()

Total 9001 -คอมพิวเตอร์  FirstPage PreviousPage NextPage LastPage CurrentPage:7/451  20-คอมพิวเตอร์/Page Goto:1 2 3 4 5 6 7 8 9 10 11 12 13