Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

마지막으로 파이썬의 키워드

<시간/>

모든 프로그래밍 언어에서 예외가 발생하는 상황을 찾습니다. Python에는 많은 내장 예외 처리 메커니즘이 있습니다. 이 예외 이름으로 처리되는 오류가 있습니다. 파이썬에는 또한 예외 처리 여부에 관계없이 실행되는 finally라는 블록이 있습니다.

구문

try:
   # main python Code....
except:
   # It is optional block
   # Code to handle exception
finally:
   # This Code that is always executed

아래 코드에서 NameError라는 예외를 봅니다. 여기에서 선언되지 않은 변수를 참조하는 코드를 만듭니다. 예외가 처리되더라도 코드는 여전히 "finally" 블록으로 실행됩니다. "finally" 블록의 코드도 실행됩니다.

try:
   var1 = 'Tutorials'
   # NameError is raised
   print(var2)

# Handle the exception
except NameError:
   print("variable is not found in local or global scope.")
finally:
   # Regardless of exception generation,
   # this block is always executed
   print('finally block code here')

출력

위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -

variable is not found in local or global scope.
finally block code here

예외 처리 없음

예외를 처리하지 않도록 코드를 설계한다고 가정합니다. 그래도 finally 블록은 처리되지 않은 예외에 대한 코드를 실행합니다.

예시

try:
   var1 = 'Tutorials'
   # NameError is raised
   print(var2)
# No exception handling
finally:
   # Regardless of exception generation,
   # this block is always executed
   print('finally block code here')

출력

위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -

finally block code here
Traceback (most recent call last):
   File "xxx.py", line 4, in
      print(var2)
NameError: name 'var2' is not defined