>  기사  >  백엔드 개발  >  Python의 예외 처리 예제 분석

Python의 예외 처리 예제 분석

WBOY
WBOY앞으로
2023-05-16 14:28:061477검색

    1. 예외란 무엇입니까

    파이썬에서 오류로 인해 발생하는 예외는 다음과 같습니다.

    Python의 예외 처리 예제 분석

    2. 예외의 유형

    파이썬의 다양한 예외는 다양한 유형, 즉 예외 식별로 식별할 수 있습니다. 실수.

    1. 일반적인 예외 클래스

    • AttributeError foo.x와 같은 객체가 없는 트리에 액세스하려고 하지만 foo에 속성이 없습니다.

      ImportError 모듈이나 패키지를 가져올 수 없거나 기본적으로 경로 문제가 있습니다. name
    • IndentationError 구문 오류(하위 클래스); 코드가 제대로 정렬되지 않았습니다.
    • IndexError x에 세 개의 요소만 있지만 액세스를 시도한 경우와 같이 첨자 인덱스가 시퀀스 경계를 ​​초과합니다.
    • SyntaxError Python 코드는 불법이며 코드를 컴파일할 수 없습니다. (개인적으로 구문 오류 및 오타라고 생각합니다.)

    • TypeError 들어오는 개체 유형이 요구 사항을 충족하지 않습니다.

    • UnboundLocalError 아직 설정되지 않은 로컬에 액세스하려고 합니다. 변수, 기본적으로 동일한 이름을 가진 다른 전역 변수가 있기 때문에 해당 변수에 액세스하고 있다고 생각하게 됩니다.

    • ValueError는 값 유형이 올바른데도 호출자가 예상하지 못한 값을 전달합니다.

    • 2 . 예외 예 :

      # TypeError:int类型不可迭代
      for i in 3:
          pass
      
      # ValueError
      num=input(">>: ") #输入hello
      int(num)
      
      # NameError
      aaa
      
      # IndexError
      l=['egon','aa']
      l[3]
      
      # KeyError
      dic={'name':'egon'}
      dic['age']
      
      # AttributeError
      class Foo:pass
      Foo.x
      
      # ZeroDivisionError:无法完成计算
      res1=1/0
      res2=1+'str'

      3. 예외 처리
    • 1. 기본 구문 try... Except

      try:
          被检测的代码块
      except 异常类型:
          try中一旦检测到异常,就执行这个位置的逻辑

    • try:
          f = [ 'a', 'a', 'a','a','a', 'a','a',]
          g = (line.strip() for line in f) #元组推导式
          print(next(g))
          print(next(g))
          print(next(g))
          print(next(g))
          print(next(g))
      except StopIteration:
          f.close()
    • 예외 클래스는 지정된 예외를 처리하는 데만 사용할 수 있습니다.

      s1 = 'hello'
      try:
          int(s1)
      except IndexError as e:  # 未捕获到异常,程序直接报错
          print(e)

      2. 다중 분기 제외..제외 및 보편적 예외: Exception
    • s1 = 'hello'
      try:
          int(s1)
      except IndexError as e:
          print(e)
      except KeyError as e:
          print(e)
      except ValueError as e:
          print(e)
      except Exception as e:
          print(e)
    • 3. try/excess...else

      try/제외 문에도 선택적인 else 절이 있습니다. 그런 다음 모든 Except 절 뒤에 배치되어야 합니다.
    • else 절은 try 절에서 예외가 발생하지 않을 때 실행됩니다.

      for arg in sys.argv[1:]:
          try:
              f = open(arg, 'r')
          except IOError:
              print('cannot open', arg)
          else:
              print(arg, 'has', len(f.readlines()), 'lines')
              f.close()

      4. 예외의 최종 실행 finally
    try-finally 문은 예외 발생 여부에 관계없이 최종 코드를 실행합니다.

    청소 동작 정의:

    s1 = 'hello'
    try:
        int(s1)
    except IndexError as e:
        print(e)
    except KeyError as e:
        print(e)
    except ValueError as e:
        print(e)
    #except Exception as e:
    #    print(e)
    else:
        print('try内代码块没有异常则执行我')
    finally:
        print('无论异常与否,都会执行该模块,通常是进行清理工作')

    #기본 10인 int()에 대한 잘못된 리터럴: 'hello'

    # 예외 여부에 관계없이 이 모듈은 일반적으로 청소를 위해 실행됩니다.

    4. 예외 던지기 raise

    Python은 raise 문을 사용하여 지정된 예외를 발생시킵니다.

    raise의 구문 형식은 다음과 같습니다.

    raise [Exception [, args [, traceback]]]
    try:
        raise TypeError('抛出异常,类型错误')
    except Exception as e:
        print(e)

    raise 유일한 매개 변수는 throw될 예외를 지정합니다. 예외 인스턴스이거나 예외 클래스(즉, Exception의 하위 클래스)여야 합니다.

    이 예외가 발생했는지 알고 싶고 이를 처리하고 싶지 않은 경우 간단한 raise 문으로 예외를 다시 발생시킬 수 있습니다.

    try:
            raise NameError('HiThere')
        except NameError:
            print('An exception flew by!')
            raise
       
    #An exception flew by!
    #Traceback (most recent call last):
    #  File "", line 2, in ?
    #NameError: HiThere

    5. 사용자 정의 예외

    새로운 예외 클래스를 생성하여 자신만의 예외를 가질 수 있습니다. 예외 클래스는 Exception 클래스에서 직접 또는 간접적으로 상속합니다. 예를 들면 다음과 같습니다.

    이 예에서는 Exception 클래스의 기본 __init__()가 재정의됩니다.

    class EgonException(Exception):
        def __init__(self, msg):
            self.msg = msg
    
        def __str__(self):
            return self.msg
    
    
    try:
        raise EgonException('抛出异常,类型错误')
    except EgonException as e:
        print(e) 
    
    #抛出异常,类型错误

    기본 예외 클래스

    다양한 예외가 발생할 수 있는 모듈을 생성할 때 일반적인 접근 방식은 이 패키지에 대한 기본 예외 클래스를 생성한 다음 이 기본 클래스를 기반으로 다양한 오류 상황에 대한 다양한 예외를 생성하는 것입니다. :

    대부분의 예외 이름은 표준 예외 이름 지정과 마찬가지로 "Error"로 끝납니다.

    class Error(Exception):
        """Base class for exceptions in this module."""
        pass
     
    class InputError(Error):
        """Exception raised for errors in the input.
     
        Attributes:
            expression -- input expression in which the error occurred
            message -- explanation of the error
        """
     
        def __init__(self, expression, message):
            self.expression = expression
            self.message = message
     
    class TransitionError(Error):
        """Raised when an operation attempts a state transition that's not
        allowed.
     
        Attributes:
            previous -- state at beginning of transition
            next -- attempted new state
            message -- explanation of why the specific transition is not allowed
        """
     
        def __init__(self, previous, next, message):
            self.previous = previous
            self.next = next
            self.message = message

    6. Assert

    assert(assert)는 표현식을 판단하고 표현식 조건이 false일 때 예외를 발생시키는 데 사용됩니다.

    어설션은 프로그램 실행 후 프로그램이 충돌할 때까지 기다릴 필요 없이 프로그램 실행 조건이 충족되지 않을 때 직접 오류를 반환할 수 있습니다.

    구문 형식은 다음과 같습니다.

    assert expression

    if not expression:
        raise AssertionError

    assert와 동일합니다. 매개변수도 뒤에 올 수 있습니다.

    assert expression [, arguments]

    if not expression:
        raise AssertionError(arguments)

    와 동일합니다. 다음 예에서는 현재 시스템이 Linux인지 확인합니다. 조건이 충족되지 않으면 직접 트리거됩니다. 예외이므로 다음 코드를 실행할 필요가 없습니다.

    import sys
    assert ('linux' in sys.platform), "该代码只能在 Linux 下执行"
    # 接下来要执行的代码
    
    # Traceback (most recent call last):
    #    File "C:/PycharmProjects/untitled/run.py", line 2, in 
    #      assert ('linux' in sys.platform), "该代码只能在 Linux 下执行"
    #  AssertionError: 该代码只能在 Linux 下执行

    위 내용은 Python의 예외 처리 예제 분석의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

    성명:
    이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제