Exceptions · 예외 처리
When things go wrong
- A runtime error normally crashes the program.
- An exception is Python's signal that something went wrong.
- Exception handling lets you catch it and keep running.
오류 발생 시
- 실행 중 오류는 일반적으로 프로그램을 종료시킵니다.
- 예외는 무언가가 잘못되었음을 Python이 알리는 신호입니다.
- 예외 처리를 사용하면 이를 포착하여程序的을 계속 실행할 수 있습니다.
try / except
- Put risky code in a
try:block. - If it raises an exception, the
except:block runs instead of crashing. - If nothing goes wrong, the
exceptblock is skipped.
try / except
- 위험한 코드를
try:블록에 넣으십시오. - 예외가 발생하면 프로그램이 종료되는 대신
except:블록이 실행됩니다. - 문제가 없으면
except블록은 건너뜁니다.
try:
number = int("not a number")
except ValueError:
number = 0
print(number)
Catch the right error
- Name the type of error you expect:
except ValueError:. ValueErroris bad text for a number;ZeroDivisionErroris divide by zero.- Catching a specific type means you do not hide other bugs.
올바른 오류 포착하기
- 예상하는 오류의 유형을 명시하십시오:
except ValueError:. ValueError는 숫자를 위한 나쁜 텍스트입니다;ZeroDivisionError는 0으로 나누기 오류입니다.- 특정 유형을 포착하면 다른 버그를 숨기지 않습니다.
try:
print(10 / 0)
except ZeroDivisionError:
print("Cannot divide by zero")
finally and raise
- A
finally:block always runs, error or not — good for cleanup. raiselets you signal an error on purpose.raise ValueError("message")stops the code unless something catches it.
finally 및 raise
finally:블록은 오류 유무와 상관없이 항상 실행되며, 정리 작업에 적합합니다.raise를 통해 의도적으로 오류를Signal할 수 있습니다.raise ValueError("message")는 포착되지 않는 한 코드를 중단시킵니다.
try:
raise ValueError("bad value")
except ValueError as e:
print("Caught:", e)
finally:
print("Always runs")
Why it matters
- A robust program should not crash on bad input.
- Handling exceptions lets it warn the user and carry on.
- It also makes sure files and other resources are closed cleanly.
중요성
- 견고한 프로그램은 잘못된 입력에서도 종료되어서는 안 됩니다.
- 예외 처리를 통해 사용자에게 경고하고 계속 진행할 수 있습니다.
- 또한 파일 및 기타 자원이 깔끔하게 닫히도록 보장합니다.
Common mistakes
- Catch a specific error (
except ValueError:), not a bareexcept:. - Put only the risky line inside the
try.
흔한 실수
- 특정한 오류(
except ValueError:)를 포착하고, 비포장된except:를 피하십시오. - 위험한 줄만
try블록 안에 넣으십시오.
Now you try
- Use
try/except(andraisein the last task). - Press Check answer to test your code.
이제 직접 해보기
try/except(마지막 작업에서는raise)를 사용하십시오.- Answer 확인 버튼을 눌러 코드를 테스트하세요.
try / except
Code runs in try; if it fails, control jumps to except. · 코드는 try 블록 내에서 실행되며, 실패할 경우 제어 흐름이 except로 이동합니다.
Write safe_int(text) that returns int(text). If the text is not a valid number, catch the ValueError and return -1 instead. · safe_int(text)을 작성하여 반환값이 int(text)이 되도록 하세요. 텍스트가 유효한 숫자가 아닌 경우 ValueError을 포착하고 대신 -1을 반환합니다.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Write divide(a, b) that returns a / b. If b is 0, catch the ZeroDivisionError and return None instead. · divide(a, b)을 작성하여 반환값이 a / b이 되도록 하세요. 만약 b이 0인 경우, ZeroDivisionError을 포착하고 대신 None을 반환합니다.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Write withdraw(balance, amount). If amount is more than balance, raise ValueError. Otherwise return the new balance (balance - amount). · withdraw(balance, amount)을 작성하세요. 만약 amount이 balance보다 크면, raise ValueError합니다. 그렇지 않으면 새로운 잔고(balance - amount)를 반환합니다.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.