-
[Python tutorial] 17. Try...Except코딩/Python 2022. 12. 21. 17:17728x90
Try Except
- try: 에러 발생 확인을 위한 테스트. 에러가 생겼을 때 'exception' 호출
- except: 에러 발생한 경우의 실행문
- else: 에러가 없을 경우 실행문
- finally: 에러 발생 유무에 관계없이 실행
try: print("Hello") except: print("Something went wrong") else: print("Nothing went wrong") Finally
try: f = open("demofile.txt") try: f.write("Lorum Ipsum") except: print("Something went wrong when writing to the file") finally: f.close() except: print("Something went wrong when opening the file")
Raise an exception
x = -1 if x < 0: raise Exception("Sorry, no numbers below zero")
x = "hello" if not type(x) is int: raise TypeError("Only integers are allowed")
728x90'코딩 > Python' 카테고리의 다른 글
[Python tutorial] 19. Built-in Function (0) 2022.12.21 [Python tutorial] 18. File handling (0) 2022.12.21 [Python tutorial] 16. Classes, Objects and Inheritance (1) 2022.12.21 [Python tutorial] 15. Lambda (0) 2022.12.21 [Python tutorial] 14. Functions (0) 2022.12.21