0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonで出てくるSyntax ErrorとExceptionと簡易対応策をざっくり

Last updated at Posted at 2015-12-16

#SyntaxError?Exception?
Syntax Error - 書いたscriptに問題有り
Exception / value error - userもしくはuser inputに問題有り

##エラー対応策
Exceptionはつきもの。全てのユーザーが必ずしもこちらが指定したルールを守ってくれるとは限らない。のでwhile True:tryを使って適当な対応策を作ってみる。

while True:
	try:
		number = int(input("what is your favorite number?"))
		print(18/number)
		break
	except valueError: #これでプログラムがErrorを吐かずにすむ
		print("Make sure you enter number")

Zero division Error - 何か数字を0で割った時に起こるエラー。

except Zerodivision Error:
    print("Don't pick zero")

もしくはexcept: breakで問題が起きた瞬間に切っちゃうこともできるが問題の特定ができなくなるのであまり推奨はされていないようだ。

##追記
こちらでも似たようなエラーの対応策について触れていたので備忘録として追記。

def div42by(divideBy):
    try:
        return 42 / divideBy
    except ZeroDivisionError:
        print('Error: You tried to divide by zero.')

print(div42by)(2)) #21
print(div42by)(0)) #Error: You tried to divide by zero.
print('How many cats do you have?')
numCats = input()
try:
	if int(numCats) >= 4:
		print('that is a lot of cats')
	else:
		print('that is not that many cats')
except ValueError:
	print('you did not enter a number')
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?